Painting a Grid With Three Different Colors - Problem
Grid Painting Challenge: You're tasked with painting an 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
Grid Coloring: From Brute Force to Dynamic ProgrammingBrute Force Approach:Try all 3^(mร—n) combinationsOne possibilityof 3^6 = 729 totalDP Approach:Column patterns + transitionsCol 1PatternCol 2PatternCol 3PatternTrack valid transitionsDynamic Programming State TableColumn:123nPattern RG:124dp[RG]Pattern RB:135dp[RB]Pattern GR:113dp[GR]... (all 3^m valid patterns)Total = ฮฃ dp[pattern] for column ntransition๐ŸŽฏ Key Insight: Pattern Recognition + State Compression = Polynomial Time!
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!
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 25 Apple 18
48.2K Views
Medium-High Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen