Skip to content

Commit 9ea8d4e

Browse files
Merge pull request #2090 from CodingTestStudy2/이진희
[이진희] Day26
2 parents c63a831 + cdd86c1 commit 9ea8d4e

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.Arrays;
2+
3+
class Solution {
4+
private static final int MOD = 1_000_000_007;
5+
private final int[][] moves = {
6+
{4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9},
7+
{}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}
8+
};
9+
10+
private int[][] memo;
11+
12+
public int knightDialer(int n) {
13+
if (n == 1) return 10;
14+
15+
memo = new int[n + 1][10];
16+
for (int[] row : memo) {
17+
Arrays.fill(row, -1);
18+
}
19+
20+
int totalWays = 0;
21+
22+
for (int i = 0; i < 10; i++) {
23+
totalWays = (totalWays + backtrack(n - 1, i)) % MOD;
24+
}
25+
26+
return totalWays;
27+
}
28+
29+
private int backtrack(int remain, int digit) {
30+
31+
if (remain == 0) {
32+
return 1;
33+
}
34+
35+
36+
if (memo[remain][digit] != -1) {
37+
return memo[remain][digit];
38+
}
39+
40+
int count = 0;
41+
for (int nextDigit : moves[digit]) {
42+
count = (count + backtrack(remain - 1, nextDigit)) % MOD;
43+
}
44+
45+
return memo[remain][digit] = count;
46+
}
47+
}

0 commit comments

Comments
 (0)