Solution:
Let X, Y, Z be the three directions in which the moth can initially go. We can symbolize the trajectory of the moth by a sequence of X's, Y's, and Z's in the obvious way: whenever the moth takes a step in a direction parallel or opposite to X, we write down X, and so on.
The moth can reach B in either exactly 3 or exactly 5 steps. A path of length 3 must be symbolized by XYZ in some order. There are 3!=6 such orders.
A trajectory of length 5 must be symbolized by XYZXX, XYZYY, or XYZZZ, in some order. There are 3⋅3!1!1!5!=3⋅20=60 possibilities here. However, we must remember to subtract out those trajectories that already arrive at B by the 3rd step: there are 3⋅6=18 of those.
The answer is thus 60−18+6=48.