Skip to content

Commit 9e246fd

Browse files
author
Tony
committed
1411.number-of-ways-to-paint-n-3-grid.py
1 parent 5b5aef4 commit 9e246fd

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#
2+
# @lc app=leetcode id=1411 lang=python3
3+
#
4+
# [1411] Number of Ways to Paint N × 3 Grid
5+
#
6+
7+
# @lc code=start
8+
import numpy as np
9+
10+
11+
class Solution:
12+
def numOfWays(self, n: int) -> int:
13+
14+
# solution from https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/solutions/575485/c-python-o-logn-time/
15+
n, mod = n - 1, 10**9 + 7
16+
M = np.matrix([[3, 2], [2, 2]])
17+
res = [6, 6]
18+
while n:
19+
if n % 2:
20+
res = res * M % mod
21+
M = M * M % mod
22+
# Fix per https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/solutions/575485/c-python-o-logn-time/comments/673840
23+
n //= 2
24+
return (np.sum(res)) % mod
25+
# ---------------------------------
26+
27+
row_perm = []
28+
for a in range(3):
29+
for b in range(3):
30+
if b != a:
31+
for c in range(3):
32+
if c != b:
33+
row_perm.append((a, b, c))
34+
35+
row_transitions = { rp: [] for rp in row_perm }
36+
for rp in row_perm:
37+
for trp in row_perm:
38+
can_place = True
39+
for i in range(3):
40+
if rp[i] == trp[i]:
41+
can_place = False
42+
break
43+
if can_place:
44+
row_transitions[rp].append(trp)
45+
46+
q = row_perm
47+
i = 1
48+
cases = 0
49+
while len(q) > 0:
50+
nq = []
51+
for p in q:
52+
if i == n:
53+
cases += 1
54+
else:
55+
nq.extend(row_transitions[p])
56+
q = nq
57+
i += 1
58+
return cases
59+
# @lc code=end
60+
61+
from test_utils import run_test
62+
63+
method = Solution().numOfWays
64+
65+
run_test(method, [1], 12)
66+
run_test(method, [5], 5110)
67+
run_test(method, [10], 5110)
68+
run_test(method, [50], 5110)
69+
run_test(method, [100], 5110)
70+
run_test(method, [5000], 30228214)
71+

0 commit comments

Comments
 (0)