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
| class Solution { public: const int MOD = 1000000007; int memo[1000][1024]; int m, n; int colorTheGrid(int m, int n) { this->m = m, this->n = n; return dp(0, 0); } int dp(int c, int prevColMask) { if (c == n) return 1; if (memo[c][prevColMask]) return memo[c][prevColMask]; vector<int> neighbors; dfs(0, prevColMask, 0, neighbors); int ans = 0; for (int nei : neighbors) ans = (ans + dp(c + 1, nei)) % MOD; return memo[c][prevColMask] = ans; } void dfs(int r, int prevColMask, int currColMask, vector<int>& ans) { if (r == m) { ans.emplace_back(currColMask); return; } for (int i = 1; i <= 3; ++i) if (getColor(prevColMask, r) != i && (r == 0 || getColor(currColMask, r - 1) != i)) dfs(r + 1, prevColMask, setColor(currColMask, r, i), ans); } int getColor(int mask, int pos) { return (mask >> (2 * pos)) & 3; } int setColor(int mask, int pos, int color) { return mask |= (color << (2 * pos)); } };
|