-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0756-pyramid-transition-matrix.py
More file actions
46 lines (35 loc) · 1.14 KB
/
0756-pyramid-transition-matrix.py
File metadata and controls
46 lines (35 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# time complexity: O(A ^ N)
# space complexity: O(n^2)
from typing import List
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
tab = defaultdict(set)
for u, v, w in allowed:
tab[u, v].add(w)
def add_neighbor(node):
res = ['']
for i in range(1, len(node)):
eles = tab[(node[i - 1], node[i])]
if eles:
res = [a + e for e in eles for a in res]
else:
return []
return res
visited = set()
def dfs(node):
if len(node) == 1:
return True
if node in visited:
return False
for nxt in add_neighbor(node):
if dfs(nxt):
return True
visited.add(node)
return False
return dfs(bottom)
bottom = "BCD"
allowed = ["BCC", "CDE", "CEA", "FFF"]
print(Solution().pyramidTransition(bottom, allowed))
bottom = "AAAA"
allowed = ["AAB", "AAC", "BCD", "BBE", "DEF"]
print(Solution().pyramidTransition(bottom, allowed))