Painting a Grid With Three Different Colors - Problem
Grid Painting Challenge: You're tasked with painting an
Think of it like creating a colorful mosaic where every cell must be painted, but neighboring cells (horizontally or vertically adjacent) must have different colors. You need to count all possible ways to paint the entire grid following this rule.
Goal: Return the total number of valid coloring arrangements modulo
m ร n grid using exactly three colors: red, green, and blue. The challenge? No two adjacent cells can have the same color!Think of it like creating a colorful mosaic where every cell must be painted, but neighboring cells (horizontally or vertically adjacent) must have different colors. You need to count all possible ways to paint the entire grid following this rule.
Goal: Return the total number of valid coloring arrangements modulo
109 + 7. Input & Output
example_1.py โ Small Grid
$
Input:
[1, 1]
โบ
Output:
3
๐ก Note:
For a 1ร1 grid, we can paint the single cell red, green, or blue. All 3 ways are valid since there are no adjacent cells to conflict with.
example_2.py โ Row of Two
$
Input:
[1, 2]
โบ
Output:
6
๐ก Note:
For a 1ร2 grid (two cells in a row), we have 3 choices for the first cell and 2 choices for the second cell (any color except the first cell's color). Total: 3 ร 2 = 6 ways.
example_3.py โ Column of Two
$
Input:
[2, 1]
โบ
Output:
6
๐ก Note:
For a 2ร1 grid (two cells in a column), similar to the row case: 3 choices for the top cell and 2 choices for the bottom cell. Total: 3 ร 2 = 6 ways.
Constraints
- 1 โค m โค 5
- 1 โค n โค 1000
- Answer fits in 32-bit integer after modulo operation
- Grid cells must be painted with exactly one of three colors
- No two adjacent cells (horizontally or vertically) can have the same color
Visualization
Tap to expand
Understanding the Visualization
1
Identify Valid Patterns
Find all ways to color a single column with no adjacent same colors
2
Build Transition Rules
Determine which column patterns can be placed next to each other
3
Dynamic Programming
Count ways to reach each pattern in the current column from previous column
4
Accumulate Results
Sum all possibilities in the final column
Key Takeaway
๐ฏ Key Insight: Instead of checking all 3^(mรn) colorings, we recognize that only the previous column pattern matters for the next column. This transforms an exponential problem into a polynomial one!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code