- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 42 lines of Java from the credited upstream file 935.java.
- The implementation visibly relies on sequence storage, cached states.
- 6 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int knightDialer(int n) {3 final int[][] DIRS = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};4 final int MOD = 1_000_000_007;5 6 int[][] dp = new int[4][3];7 Arrays.stream(dp).forEach(A -> Arrays.fill(A, 1));8 dp[3][0] = dp[3][2] = 0;9 10 for (int k = 0; k < n - 1; ++k) {11 int[][] newDp = new int[4][3];12 for (int i = 0; i < 4; ++i)13 for (int j = 0; j < 3; ++j) {14 if (isNotNumericCell(i, j))15 continue;16 for (int[] dir : DIRS) {17 final int x = i + dir[0];18 final int y = j + dir[1];19 if (x < 0 || x >= 4 || y < 0 || y >= 3)20 continue;21 if (isNotNumericCell(x, y))22 continue;23 newDp[i][j] = (newDp[i][j] + dp[x][y]) % MOD;24 }25 }26 dp = newDp;27 }28 29 int ans = 0;30 31 for (int[] row : dp)32 for (final int a : row)33 ans = (ans + a) % MOD;34 35 return ans;36 }37 38 private boolean isNotNumericCell(int i, int j) {39 return i == 3 && (j == 0 || j == 2);40 }41}42