重新写一个bfs算法的python代码
时间: 2023-04-04 19:03:03 浏览: 138
Python实现BFS算法
好的,以下是一个BFS算法的Python代码:
```
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
# 示例用法
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
print(bfs(graph, 'A'))
```
希望这个代码对你有帮助!
阅读全文