Number of Ways to Paint N × 3 Grid - Problem
You have a grid of size n × 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green.
The constraint is that no two adjacent cells can have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).
Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.
Input & Output
Example 1 — Single Row
$
Input:
n = 1
›
Output:
12
💡 Note:
For a 1×3 grid, we have 3 choices for first cell, 2 for second (different from first), and 2 for third (different from second). However, we need to consider both ABA patterns (6 ways) and ABC patterns (6 ways), giving total 12 ways.
Example 2 — Two Rows
$
Input:
n = 2
›
Output:
54
💡 Note:
Starting with 12 ways for first row (6 ABA + 6 ABC), each pattern can transition to valid patterns in the second row based on transition rules.
Example 3 — Three Rows
$
Input:
n = 3
›
Output:
246
💡 Note:
Each additional row multiplies the possibilities based on valid color transitions from the previous row patterns.
Constraints
- 1 ≤ n ≤ 5000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code