You have a grid with n rows and 3 columns. You want to paint every cell with exactly one of three colors (Red, Yellow or Green) so that no two adjacent cells have the same color. Two cells are adjacent when they share a vertical or horizontal side.
Given n, return the number of ways to paint the grid. The answer can be large, so return it modulo 10^9 + 7.
Function Signature
def count_grid_paintings(n: int) -> int:
Rules
-
Cells that touch only at a corner (diagonal neighbors) may have the same color.
-
Two paintings are different when at least one cell has a different color. Paintings that differ only by renaming the colors still count separately.
Constraints
Examples
Input: n = 1
Output: 12
The first cell can take any of 3 colors, and each of the other two cells must differ from the cell to its left, so there are 3 * 2 * 2 = 12 rows. Six of them use two colors (such as Red, Yellow, Red) and six use all three.
Input: n = 2
Output: 54
Below the row Red, Yellow, Red the valid second rows are YRY, YRG, YGY, GRY and GRG (5 rows). Below Red, Yellow, Green they are YRY, YGY, YGR and GRY (4 rows). Adding up the valid second rows for all 12 first rows gives 54.
Input: n = 3
Output: 246
Extending each of the 54 two-row paintings by every valid third row gives 246 paintings in total.