Place a knight on a phone pad, and let it hop N-1 times between the numbered keys, generating a N-digit number. Find how many distinct numbers we can dial in this manner.
The keypad:
The knight can move in 8 ways.
Solution
Let Xn,i be the number of n-digit numbers ending with digit i.
By observing the keypad, we can draw these conclusions:
A knight can’t make any hop from 5 or to 5. So the only number with digit 5 that we can dial is “5”. That is, X1,5 = 1 and Xn,5 = 0 (n > 1).
1, 3, 7, 9 are symmetrical (and the 8 moves of the knight are symmetrical). So Xn,1 = Xn,3 = Xn,7 = Xn,9.
Similarly, Xn,2 = Xn,8
Xn,4 = Xn,6
Xn+1,0 = Xn,4 + Xn,6 = 2 × Xn,4
Xn+1,1 = Xn,2 + Xn,4
Xn+1,2 = Xn,7 + Xn,9 = 2 × Xn,1
Xn+1,4 = Xn,0 + Xn,3 + Xn,9 = Xn,0 + 2 × Xn,1
Let Xn = (Xn,0, Xn,1, Xn,2, Xn,4)’, then we have: Xn+1 = A · Xn
A is a 4 by 4 matrix:
0 0 0 2 0 0 1 1 0 2 0 0 1 2 0 0
The answer is sigma Xn,i (0 ≤ i ≤ 9) = XN,0 + 4 × XN,1 + 2 × XN,2 + 2 × XN,4 (N > 1).
So we can calculate Xn,i recursively, which takes O(N) time. Or use fast power to calculate A^(N-1) and get the answer, which takes O(logN) time.