Skip to content

Commit 12ac1a8

Browse files
authored
Create 1931. Painting a Grid With Three Different Colors
1 parent 18d1812 commit 12ac1a8

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
public:
3+
int md = 1e9+7;
4+
bool isValid(int mask,int m){
5+
int prev = -1;
6+
for(int i=0;i<m;i++){
7+
int cur = mask%3;
8+
mask/=3;
9+
if(prev==cur) return false;
10+
prev = cur;
11+
}
12+
return true;
13+
}
14+
bool isCompatible(int a,int b,int m){
15+
for(int i=0;i<m;i++){
16+
if(a%3==b%3) return false;
17+
a/=3;b/=3;
18+
}
19+
return true;
20+
}
21+
int colorTheGrid(int m, int n) {
22+
int limit = pow(3,m);
23+
vector<int> validMasks;
24+
for(int i=0;i<limit;i++){
25+
if(isValid(i,m)){
26+
validMasks.push_back(i);
27+
}
28+
}
29+
map<int,vector<int>> adj;
30+
for(auto a : validMasks){
31+
for(auto b : validMasks){
32+
if(isCompatible(a,b,m)){
33+
adj[a].push_back(b);
34+
}
35+
}
36+
}
37+
map<int,int> dp;
38+
for(auto mask : validMasks){
39+
dp[mask] = 1;
40+
}
41+
42+
for(int i=1;i<n;i++){
43+
map<int,int> updatedDP;
44+
for(auto &[mask,count] : dp){
45+
for(auto nei : adj[mask]){
46+
updatedDP[nei] = (updatedDP[nei] + count)%md;
47+
}
48+
}
49+
dp = updatedDP;
50+
}
51+
52+
int ans = 0;
53+
for(auto &[x,val] : dp) ans = (ans + val)%md;
54+
55+
return ans;
56+
57+
}
58+
59+
};

0 commit comments

Comments
 (0)