import collections
def BFS(root, target):
queue = collections.deque() # 所有节点将会被放入队列等待被处理
step = 0
queue.append(root)
# BFS
while len(queue) != 0:
step += 1
# 迭代所有已经存在队列中的节点
size = len(queue)
for i in range(size):
cur = the first node in queue
return step if cur is target
while cur.next:
add next to queue
remove cur from queue
模板二:利用哈希表来解决不会访问一个节点两次
import collections
def BFS(root, target):
queue = collections.deque() # 所有节点将会被放入队列等待被处理
hash_set = {} # 记录已经访问过的,visited,
step = 0 # 记录扩散的步数
queue.append(root) # 将起点加入队列
# BFS
while len(queue) != 0:
step += 1
# 迭代所有已经存在队列中的节点
size = len(queue)
# 将当前队列中的所有节点向四周扩散
for i in range(size):
cur = the first node in queue
return step if cur is target # 判断是否到达终点
# 将相邻节点加入队列
while cur.next:
if cur not in hash_set:
add next to queue
add next to used
remove cur from queue