-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path935. Knight Dialer.java
96 lines (79 loc) · 2.54 KB
/
935. Knight Dialer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//Approach-1 (Using Recursion + Memoization)
//T.C : O(n*9) Total n*k states
//S.C : O(n*9)
public class Solution {
private static final int M = 1000000007;
private static final List<List<Integer>> adj = Arrays.asList(
Arrays.asList(4, 6),
Arrays.asList(6, 8),
Arrays.asList(7, 9),
Arrays.asList(4, 8),
Arrays.asList(3, 9, 0),
Arrays.asList(),
Arrays.asList(1, 7, 0),
Arrays.asList(2, 6),
Arrays.asList(1, 3),
Arrays.asList(2, 4)
);
private int[][] t = new int[5001][10];
private int solve(int n, int cell) {
if (n == 0) {
return 1;
}
if (t[n][cell] != -1) {
return t[n][cell];
}
int result = 0;
for (int nextCell : adj.get(cell)) {
result = (result + solve(n - 1, nextCell)) % M;
}
return t[n][cell] = result;
}
public int knightDialer(int n) {
int result = 0;
Arrays.stream(t).forEach(row -> Arrays.fill(row, -1));
for (int cell = 0; cell <= 9; cell++) {
result = (result + solve(n - 1, cell)) % M;
}
return result;
}
}
//Approach-2 (Using Bottom Up - Just write from the recursion)
//T.C : O(n*10)
//S.C : O(n*10)
public class Solution {
private static final int M = 1000000007;
private static final List<List<Integer>> adj = Arrays.asList(
Arrays.asList(4, 6),
Arrays.asList(6, 8),
Arrays.asList(7, 9),
Arrays.asList(4, 8),
Arrays.asList(3, 9, 0),
Arrays.asList(),
Arrays.asList(1, 7, 0),
Arrays.asList(2, 6),
Arrays.asList(1, 3),
Arrays.asList(2, 4)
);
public int knightDialer(int n) {
int result = 0;
// t[i][j] = number of ways to form a number of length i when I am currently at cell j
int[][] t = new int[n][10];
for (int cell = 0; cell < 10; cell++) {
t[0][cell] = 1; // for n == 0, we always return 1
}
for (int i = 1; i < n; i++) { // This is the length of the number
for (int cell = 0; cell <= 9; cell++) {
int ans = 0;
for (int nextCell : adj.get(cell)) {
ans = (ans + t[i - 1][nextCell]) % M;
}
t[i][cell] = ans;
}
}
for (int cell = 0; cell <= 9; cell++) {
result = (result + t[n - 1][cell]) % M;
}
return result;
}
}