这是一类典型的bfs问题,希望下次遇到我能回
import collections
class Solution(object):
def openLock1(self, deadends, target):
dead_set = set(deadends)
queue = collections.deque()
queue.append(("0000", 0))
visited = {"0000"}
while queue:
number, depth = queue.popleft()
if number == target:
return depth
if number in dead_set:
continue
for item in self.neighbors(number):
# 如果该节点访问过了,再次访问会导致死循环
if item not in visited:
visited.add(item)
queue.append((item, depth + 1))
return -1
def neighbors(self, number):
for i in range(len(number)):
cur = int(number[i])
for drift in (-1, 1):
temp = (cur + drift) % 10
yield number[:i] + str(temp) + number[i+1:]
def openLock(self, deadends, target):
dead_set = set(deadends)
start_set = {"0000"}
target_set = {target}
visited_set = set()
depth = 0
while start_set and target_set:
temp = set()
for cur in start_set:
if cur in dead_set:
continue
if cur in target_set:
return depth
visited_set.add(cur)
for item in self.neighbors(cur):
if item not in visited_set:
temp.add(item)
depth += 1
start_set = target_set
target_set = temp
return -1
if __name__ == '__main__':
deadends = ["0201", "0101", "0102", "1212", "2002"]
target = "0202"
s1 = Solution()
root = s1.openLock(deadends, target)
print(root)