一个图的广度优先和深度优先遍历的python代码
时间: 2023-06-23 07:50:50 浏览: 101
图的遍历 广度优先和深度优先
好的,下面是一个无向图的广度优先遍历和深度优先遍历的Python代码示例:
```python
from collections import deque
# 定义一个无向图
graph = {
'A': ['B', 'C', 'D'],
'B': ['A', 'E'],
'C': ['A', 'F'],
'D': ['A', 'G'],
'E': ['B'],
'F': ['C'],
'G': ['D']
}
# 广度优先遍历
def bfs(graph, start):
queue = deque()
visited = set()
queue.append(start)
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
print(node)
for neighbor in graph[node]:
queue.append(neighbor)
# 深度优先遍历
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# 测试
print("广度优先遍历:")
bfs(graph, 'A')
print("深度优先遍历:")
dfs(graph, 'A')
```
其中,广度优先遍历使用了队列`deque`,深度优先遍历使用了递归。在这个示例中,我们定义了一个无向图`graph`,以字典的形式表示图的邻接表。我们从顶点`A`开始遍历,先进行广度优先遍历,然后进行深度优先遍历,输出遍历的结果。
阅读全文