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