leetcode題解記錄-752開啟轉盤鎖(python3)

Cris_Lee卡卡卡發表於2020-10-28

題目

開啟轉盤鎖
題目連結
官方題解

關鍵詞

廣度優先遍歷(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 

相關文章