这题的思路比较清晰。主要就是用一个字母来代替两个字母,递归代替,最后看能不能只剩下一个字母。后来发现我其实是用的是BFS,所以这题也可以用DFS。(昨天搞竞赛忘了发。。。)附代码:
class Solution:
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
if len(bottom) == 1:
return True
re = []
for i in range(0, len(bottom)-1):
temp = bottom[i:i+2]
temp_list = []
for allow in allowed:
if temp == allow[0:2]:
temp_list.append(allow[2])
re.append(temp_list)
num = 1
for r in re:
num *= len(r)
result = [""] * num
for r in re:
length = len(r)
for i in range(length):
for j in range(int(num/length)):
result[i*int(num/length)+j] += r[i]
sign = False
for r in result:
sign = sign or self.pyramidTransition(r, allowed)
if sign:
return True
return False