Problem Description
Given an m x n grid where each cell is initially white, you need to paint each cell with one of three colors: red, green, or blue. The painting must be done such that no two adjacent cells (horizontally or vertically) share the same color. Every cell must be painted. Return the number of valid ways to color the grid modulo 10^9 + 7.
Key Insights
- Since m is small (m ≤ 5) but n can be large (n ≤ 1000), it is efficient to treat each column as a state.
- Precompute all valid color configurations for a single column (ensuring vertical adjacent cells differ).
- For any two consecutive columns, ensure that colors in corresponding rows (horizontal adjacent cells) are different.
- Use dynamic programming where dp[i] represents the number of ways to paint up to the current column ending with the i‑th valid state.
- Precompute valid transitions between states to avoid repeated checks.
Space and Time Complexity
Time Complexity: O(n * S^2) where S is the number of valid states (at most 3 * 2^(m-1)).
Space Complexity: O(S^2 + S) for storing state transition information and DP arrays.
Solution
We solve the problem using a dynamic programming (DP) approach on columns:
- Generate all valid states for a column of height m ensuring vertical adjacent cells are painted with different colors.
- Precompute a 2D boolean matrix capturing whether state i is compatible with state j for adjacent columns (i.e., for every row, the color in state i is different from the color in state j).
- Initialize the DP array with 1 for each valid state as the first column can be painted in any valid configuration.
- For each subsequent column, update the DP counts using the precomputed transitions.
- Finally, return the sum of the DP array values modulo 10^9 + 7.
Below are solutions in Python, JavaScript, C++, and Java with detailed comments.