(5) A moving point $P$ starts from vertex $A$ of a square $A B C D$ with side length 1, travels in sequence through $B, C, D$ and returns to point $A$, after which the motion ends. Let $x$ represent the distance traveled by point $P$, and $f(x)$ represent the distance between $P$ and $A$. Find the function $f(x)$.
(5) $\left\{\begin{array}{ll}x, & 0 \leqslant x \leqslant 1, \\ \sqrt{1+(x-1)^{2}}, & 1<x \leqslant 2, \\ \sqrt{1+(3-x)^{2}}, & 2<x \leqslant 3, \\ 4-x, & 3<x \leqslant 4\end{array}\right.$