Use arrays to track counts at the current and previous hops. Sum all digits at the end.
function knightDialer(n):
MOD = 10^9 + 7
moves = {
0: [4,6], 1: [6,8], 2: [7,9], 3: [4,8], 4: [0,3,9],
5: [], 6: [0,1,7], 7: [2,6], 8: [1,3], 9: [2,4]
}
prev = [1] * 10
for hop in range(1, n):
curr = [0] * 10
for digit in range(10):
for src in moves[digit]:
curr[digit] = (curr[digit] + prev[src]) % MOD
prev = curr
return sum(prev) % MOD
time, space (fixed-size arrays).