广度优先遍历-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)
时刻记着自己要成为什么样的人!