图的遍历python
时间: 2023-07-09 19:19:06 浏览: 86
图的遍历可以使用深度优先搜索(DFS)和广度优先搜索(BFS)等算法。
以下是一个使用邻接表表示图的DFS遍历的Python代码示例:
```python
# 图的邻接表表示
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
# DFS遍历
visited = set()
def dfs(node):
visited.add(node)
print(node, end=' ')
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor)
dfs('A')
```
输出结果为:A B D E F C
以下是一个使用邻接表表示图的BFS遍历的Python代码示例:
```python
# 图的邻接表表示
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
# BFS遍历
visited = set()
queue = []
def bfs(node):
visited.add(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s, end=' ')
for neighbor in graph[s]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
bfs('A')
```
输出结果为:A B C D E F
阅读全文