Example 7 There are $n$ squares arranged in a row, each square is to be colored with one of the three colors: red, yellow, or blue, with each square being one color. It is required that any adjacent squares must be of different colors, and the first and last squares must also be of different colors. How many ways are there to color the squares?

---

The translation maintains the original text's line breaks and format as requested.
Solution: Let there be $a_{n}$ different ways of coloring. It is easy to get $a_{1}=3$, $a_{2}=6, a_{3}=6$, and when $n \geqslant 4$, after numbering the $n$ squares in sequence, square 1 and square $(n-1)$ are not adjacent.
(1) If square $(n-1)$ and square 1 are colored differently, at this time, square $n$ has only 1 color to choose from, and the first $n-1$ squares satisfy the condition that the first and last squares are different colors, so there are $a_{n-1}$ different ways of coloring.
(2) If square $(n-1)$ and square 1 are colored the same, at this time, square $(n-2)$ and square 1 must be colored differently, otherwise square $(n-1)$ and square $(n-2)$ would be colored the same, thus, the first $n-2$ squares have $a_{n-2}$ different ways of coloring. Since square $n$ and square 1 are different colors, there are 2 ways to color it, so there are $2 a_{n-2}$ different ways of coloring.
In summary, we get the recurrence relation
$$
a_{n}=a_{n-1}+2 a_{n-2}(n \geqslant 4),
$$

and we can obtain
$$
a_{n}=2^{n}+2(-1)^{n}(n \geqslant 2) .
$$