Painting a Grid With Three Different Colors Problem
Description
LeetCode Problem 1931.
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7.
Example 1:

Input: m = 1, n = 1
Output: 3
Explanation: The three possible colorings are shown in the image above.
Example 2:

Input: m = 1, n = 2
Output: 6
Explanation: The six possible colorings are shown in the image above.
Example 3:
Input: m = 5, n = 5
Output: 580986
Constraints:
1 <= m <= 51 <= n <= 1000
Solution
Approach: Column Bitmask DP
The grid has at most 5 rows, so a column can be painted in at most 3^5 = 243 ways. Keep only the colorings in which no two vertically adjacent cells share a color, and record for each of them which colorings may stand next to it in the following column (the two columns differ in every row).
Let f[j] be the number of ways to paint the columns so far with the last column in coloring j. At first f[j] = 1 for every valid coloring. Moving to the next column, the new g[j] is the sum of f[k] over all colorings k compatible with j. Repeat this n - 1 times (a rolling array is enough) and return the sum of all f[j] modulo 10^9 + 7.
Complexity: O(3^(2m) + n * 3^(2m)) time at worst, in practice far less because only the valid colorings are paired, and O(3^m) space, where m is the number of rows.
from collections import defaultdict
class Solution:
def colorTheGrid(self, m: int, n: int) -> int:
def f1(x: int) -> bool:
last = -1
for _ in range(m):
if x % 3 == last:
return False
last = x % 3
x //= 3
return True
def f2(x: int, y: int) -> bool:
for _ in range(m):
if x % 3 == y % 3:
return False
x, y = x // 3, y // 3
return True
mod = 10**9 + 7
mx = 3**m
valid = {i for i in range(mx) if f1(i)}
d = defaultdict(list)
for x in valid:
for y in valid:
if f2(x, y):
d[x].append(y)
f = [int(i in valid) for i in range(mx)]
for _ in range(n - 1):
g = [0] * mx
for i in valid:
for j in d[i]:
g[i] = (g[i] + f[j]) % mod
f = g
return sum(f) % mod