图的广度优先搜索的python代码
时间: 2024-03-02 08:42:55 浏览: 64
python 递归深度优先搜索与广度优先搜索算法模拟实现
当然,我可以为您提供图的广度优先搜索的Python代码。以下是示例代码:
```
from queue import Queue
def bfs(graph, start):
visited = set()
queue = Queue()
visited.add(start)
queue.put(start)
while not queue.empty():
vertex = queue.get()
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.put(neighbor)
# 以下是示例图
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
bfs(graph, 'A')
```
希望这可以帮助您解决您的问题!
阅读全文