Find the number of functions $f:\{a_1,a_2...a_n\} \to \{b_1,b_2,...b_m\}$ where $n>m>3$ such that $f(a_i) \neq f(a_{i+1}), \forall i=1,2,3...(n-1)$ and $f(a_n) \neq f(a_1)$.
Attempt:
It is simple to count the number of functions satisfying the first inequality; we can map $a_1$ to any of the $m$ elements in the codomain. Accordingly, since $f(a_2) \neq f(a_1)$, $a_2$ can be mapped to any of the $(m-1)$ remaining elements. Similarly, extending this argument, $a_3,a_4,a_5...a_n$ can all be mapped to $(m-1)$ elements.
Hence, the number of functions is $m(m-1)^{n-1}$.
Now, I will obtain my desired answer if I can count all the cases where $f(a_n)=f(a_1)$ and subtract that from the above quantity. Suppose $a_1$ and $a_n$ are simultaneously mapped to the same $b_k$. This can happen in $m$ ways. Accordingly, $a_2$ can be mapped to any of the $(m-1)$ remaining elements. The above reasoning can be applied again until $a_{n-1}$ which only has $(m-2)$ possible elements to be mapped to since it cannot equal $f(a_{n})$ which has already been chosen. Hence, the number of functions will be $m(m-1)^{n-2}(m-2)$.
Accordingly, the number of functions where $f(a_n) \neq f(a_1)$ is $m(m-1)^{n-1}-m(m-1)^{n-2}(m-2)=m(m-1)^{n-2}$
However, the reported answer is $(m-1)^n+(-1)^n(m-1)$. I think I made a mistake in counting the functions where $f(a_n)=f(a_1)$ but I'm unable to find it. Can anyone point out the error and help me remedy it?
In the brief solution at the back of the book, they use a recursion $\eta(n,m)=m(m-1)^{n-1} -\eta(n-1,m)$ to count the number of functions but there's no explanation for why and I don't understand how to arrive at this recursion.