forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Ways to Paint N × 3 Grid.java
63 lines (52 loc) · 1.59 KB
/
Number of Ways to Paint N × 3 Grid.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
class Solution {
int MOD = 1000000007;
int[][] states = {{0,1,0},{1,0,1},{2,0,1},
{0,1,2},{1,0,2},{2,0,2},
{0,2,0},{1,2,0},{2,1,0},
{0,2,1},{1,2,1},{2,1,2}};
HashMap<Integer, List<Integer>> nextMap = new HashMap<>();
Long[][] memo;
public int numOfWays(int n) {
if(n == 0)
return 0;
// Graph
for(int prev = 0; prev < 12; prev++){
List<Integer> nexts = new ArrayList<>();
for(int next = 0; next < 12; next++){
if(next == prev) continue;
boolean flag = true;
for(int i = 0; i < 3; i++){
if(states[prev][i] == states[next][i]){
flag = false;
break;
}
}
if(flag)
nexts.add(next);
}
nextMap.put(prev, nexts);
}
//DFS
memo = new Long[12][n];
long ways = 0;
for(int i = 0; i < 12; i++){
ways += dfs(i, n-1);
ways %= MOD;
}
return (int)(ways);
}
long dfs(int prev, int n){
if(n == 0)
return 1;
if(memo[prev][n] != null)
return memo[prev][n];
long ways = 0;
List<Integer> nexts = nextMap.get(prev);
for(int next : nexts){
ways += dfs(next, n-1);
ways %= MOD;
}
memo[prev][n] = ways;
return ways;
}
}