LeetCode 1931. Painting a Grid With Three Different Colors Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1931. Painting a Grid With Three Different Colors

Description

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 109 + 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 <= 5
  • 1 <= n <= 1000

Solutions

Solution 1: State Compression + Dynamic Programming

We notice that the number of rows in the grid does not exceed 5, so there are at most 35=243 different color schemes in a column.

Therefore, we define f[i][j] to represent the number of schemes in the first i columns, where the coloring state of the ith column is j. The state f[i][j] is transferred from f[i - 1][k], where k is the coloring state of the i - 1th column, and k and j meet the requirement of different colors being adjacent. That is:

f[i][j] = ∑_{k ∈ valid(j)} f[i - 1][k]

where valid(j) represents all legal predecessor states of state j.

The final answer is the sum of f[n][j], where j is any legal state.

We notice that f[i][j] is only related to f[i - 1][k], so we can use a rolling array to optimize the space complexity.

The time complexity is O((m + n) × 32m), and the space complexity is O(3m). Here, m and n are the number of rows and columns of the grid, respectively.

PythonJavaC++GoTypeScript
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !