1. import collections
    2. def BFS(root, target):
    3. queue = collections.deque() # 所有节点将会被放入队列等待被处理
    4. step = 0
    5. queue.append(root)
    6. # BFS
    7. while len(queue) != 0:
    8. step += 1
    9. # 迭代所有已经存在队列中的节点
    10. size = len(queue)
    11. for i in range(size):
    12. cur = the first node in queue
    13. return step if cur is target
    14. while cur.next:
    15. add next to queue
    16. remove cur from queue

    模板二:利用哈希表来解决不会访问一个节点两次

    1. import collections
    2. def BFS(root, target):
    3. queue = collections.deque() # 所有节点将会被放入队列等待被处理
    4. hash_set = {} # 记录已经访问过的,visited,
    5. step = 0 # 记录扩散的步数
    6. queue.append(root) # 将起点加入队列
    7. # BFS
    8. while len(queue) != 0:
    9. step += 1
    10. # 迭代所有已经存在队列中的节点
    11. size = len(queue)
    12. # 将当前队列中的所有节点向四周扩散
    13. for i in range(size):
    14. cur = the first node in queue
    15. return step if cur is target # 判断是否到达终点
    16. # 将相邻节点加入队列
    17. while cur.next:
    18. if cur not in hash_set:
    19. add next to queue
    20. add next to used
    21. remove cur from queue