题目
关键词
广度优先遍历(BFS)
代码记录
BFS
class Solution:
def __init__(self):
import math
self.min_route=math.inf
self.seen={}
def openLock(self, deadends: List[str], target: str) -> int:
if '0000' in deadends:
return -1
import math
def next_step(cur_step:str)->List[str]:
res=[]
for i in range(4):
steps=[cur_step[:i]+str((int(cur_step[i])-1)%10)+cur_step[i+1:],cur_step[:i]+str((int(cur_step[i])+1)%10)+cur_step[i+1:]]
for step in steps:
if step not in deadends and step not in self.seen:
self.seen[step]=0
res.append(step)
return res
def bfs(cur_queue:List[str],cur_route:int):
to_search=[]
for i in range(len(cur_queue)):
cur_step=cur_queue[i]
if cur_step==target:
self.min_route = min(self.min_route,cur_route+1)
return
next_steps=next_step(cur_step)
to_search.extend(next_steps)
if to_search:
bfs(to_search,cur_route+1)
self.seen['0000']=0
bfs(['0000'],-1)
return -1 if self.min_route==math.inf else self.min_route