Painting a Grid With Three Different Colors — LeetCode 1931 Python Solution
HardDynamic Programming
- Problem
- #1931
- Pattern
- Dynamic Programming
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are given two integers m and n. Consider an m x n grid where each cell is initially white.
Example
- Input
- m = 1, n = 1
- Output
- 3
- Explanation
- The three possible colorings are shown in the image above.
Python solution
Python
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) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O((m + n) \times 3^{2m}) |
| Space | O(3^m) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1931. Painting a Grid With Three Different Colors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1931. Painting a Grid With Three Different Colors?
- LeetCode 1931. Painting a Grid With Three Different Colors is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1931. Painting a Grid With Three Different Colors?
- The Python solution on this page runs in O((m + n) \times 3^{2m}).
- What is the space complexity of LeetCode 1931. Painting a Grid With Three Different Colors?
- The Python solution on this page uses O(3^m) auxiliary space.
- What topics does LeetCode 1931. Painting a Grid With Three Different Colors cover?
- LeetCode 1931. Painting a Grid With Three Different Colors is tagged Dynamic Programming on LeetCode.