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 modulo109 + 7.
Example 1:
Input: m = 1, n = 1
Output: 3
Explanation: The three possible colorings are shown in the image above.
Example 2:
Input: m = 1, n = 2
Output: 6
Explanation: The six possible colorings are shown in the image above.
Example 3:
Input: m = 5, n = 5
Output: 580986
Constraints:
1 <= m <= 5
1 <= n <= 1000
Solutions
Solution 1: State Compression + Dynamic Programming
Thinking
Adjacent cells need different colors. Cell-by-cell coloring is too large, but \(m\le 5\) so a column has only \(3^m\) colorings.
We keep masks whose vertical neighbors differ, then precompute pairs of masks that also differ horizontally. \(f[j]\) is the number of ways the previous column equals \(j\), rolled forward.
The first column counts valid masks; \(n-1\) transitions follow, and the answer is the sum modulo \(10^9+7\).
We notice that the number of rows in the grid does not exceed \(5\), so there are at most \(3^5=243\) different color schemes in a column.
Therefore, we define \(f[i][j]\) to represent the number of schemes in the first \(i\) columns, where the coloring state of the \(i\)th column is \(j\). The state \(f[i][j]\) is transferred from \(f[i - 1][k]\), where \(k\) is the coloring state of the \(i - 1\)th column, and \(k\) and \(j\) meet the requirement of different colors being adjacent. That is:
where \(\textit{valid}(j)\) represents all legal predecessor states of state \(j\).
The final answer is the sum of \(f[n][j]\), where \(j\) is any legal state.
We notice that \(f[i][j]\) is only related to \(f[i - 1][k]\), so we can use a rolling array to optimize the space complexity.
The time complexity is \(O((m + n) \times 3^{2m})\), and the space complexity is \(O(3^m)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, respectively.