Update the dp array, and continue with the next iteration
class Solution:
def knightDialer(self, n: int) -> int:
dct = {
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)
}
num_keys = 10
dp = [1] * num_keys # dp[i] = number of times the knight can reach dial pad i
for _ in range(n - 1):
nxt = [0] * num_keys
for i in dct:
for j in dct[i]:
nxt[i] += dp[j]
dp = nxt
return sum(dp) % (10**9 + 7)
N: input size N
Time Complexity: O(N * number of dials in dial pad(10) * max size of dict[i] (3) ) -> O(N)
935. Knight Dialer
https://leetcode.com/problems/knight-dialer/description/
A knight could only move in either
2 horizontal + 1 vertical
or2 vertical + 1 horizontal
. Graph traversal, DP problem with N stopsi in range(n)
), create anext array of [0] * 10
wherenext[i] = count of dial pad that can be reached from dial pad i
First iteration
dp
array, and continue with the next iterationN: input size N
O(N * number of dials in dial pad(10) * max size of dict[i] (3) )
->O(N)
O(1)
with dp array of size 10