-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1931.cpp
More file actions
49 lines (48 loc) · 1.59 KB
/
1931.cpp
File metadata and controls
49 lines (48 loc) · 1.59 KB
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
class Solution {
public:
bool isVaildState(int state, int m) {
vector<int> temp;
for (int i = 0; i < m; ++i) {
int bit = state % 3;
if ((!temp.empty()) && (bit == temp.back())) return false;
temp.push_back(bit);
state /= 3;
}
return true;
}
bool isValidTransit(int state0, int state1, int m) {
for (int i = 0; i < m; ++i) {
if (state0 % 3 == state1 % 3) return false;
state0 /= 3;
state1 /= 3;
}
return true;
}
int colorTheGrid(int m, int n) {
vector<int> candidates;
long long mod = 1e9 + 7;
for (int state = 0; state < pow(3, m); ++state) {
if (isVaildState(state, m)) candidates.push_back(state);
}
vector<long long> dp(candidates.size(), 1);
vector<long long> dpTemp(candidates.size(), 0);
for (int i = 1; i < n; ++i) {
for (int curStateIdx = 0; curStateIdx < candidates.size(); ++curStateIdx) {
dpTemp[curStateIdx] = 0;
for (int preStateIdx = 0; preStateIdx < candidates.size(); ++preStateIdx) {
if (isValidTransit(candidates[preStateIdx], candidates[curStateIdx], m)) {
dpTemp[curStateIdx] += dp[preStateIdx];
dpTemp[curStateIdx] %= mod;
}
}
}
swap(dp, dpTemp);
}
long long res = 0;
for (auto& num : dp) {
res += num;
res %= mod;
}
return res;
}
};