[LeetCode] Painting a Grid With Three Different Colors

1931. Painting a Grid With Three Different Colors

You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.

Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.

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
class Solution {
int dp[1001][1000];
vector<int> comb[1000];
int N, M;
int mod = 1e9 + 7;

int getColorAt(int mask, int i) {
if(i < 0) return 0;
return (mask>>(i * 2)) & 3;
}
bool verifyBoth(int comb1, int comb2) {
for(int i = 0; i < M; i++) {
if(getColorAt(comb1, i) == getColorAt(comb2, i)) return false;
}
return true;
}
bool verifySelf(int comb) {
for(int i = 0; i < M; i++) {
if(getColorAt(comb,i) == 0) return false;
if(getColorAt(comb, i - 1) == getColorAt(comb, i)) return false;
}
return true;
}

void buildComb() {
for(int i = 1; i < 1<<(M*2); i++) {
if(verifySelf(i))
comb[0].push_back(i);
}
for(int i = 0; i < comb[0].size(); i++) {
for(int j = i + 1; j < comb[0].size(); j++) {
if(verifyBoth(comb[0][i], comb[0][j])) {
comb[comb[0][i]].push_back(comb[0][j]);
comb[comb[0][j]].push_back(comb[0][i]);
}
}
}
}

int helper(int y, int colors) {
if(y == N) return 1;

if(dp[y][colors] != -1) {
return dp[y][colors];
}
int& res = dp[y][colors] = 0;

for(auto c : comb[colors]) {
res = (res + helper(y + 1, c)) % mod;
}
return res;
}
public:
int colorTheGrid(int m, int n) {
memset(dp,-1,sizeof(dp));
N = n, M = m;
buildComb();
return helper(0,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/11/PS/LeetCode/painting-a-grid-with-three-different-colors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.