广度优先遍历-python

主体代码模板:

from collections import deque # 使用双端队列deque,Queue更为复杂不可用

def bfs():
    queue = deque([root])   # 队列数据结构实现
    visited = set(root)     # 标记访问节点
    while queue:
        cur_node = queue.popleft()
        for neighbor in cur_node.neighbors:
            if neighbor in visited:
                continue
            queue.append(neighbor)
            visited.add(neighbor)
    return list(visited)        

 

posted @ 2022-07-26 09:53  今夜无风  阅读(65)  评论(0编辑  收藏  举报