数据结构对图进行深度优先遍历的代码
时间: 2024-11-09 19:27:34 浏览: 19
深度优先遍历(Depth First Search, DFS)是一种用于遍历或搜索树形数据结构和图的算法。在Python中,可以使用递归或栈来实现DFS。这里是一个基本的使用邻接列表表示无向图的DFS例子:
```python
from collections import defaultdict
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
# 标记当前节点为已访问
visited.add(start)
print(f"Visiting {start}")
# 遍历所有相邻的节点
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# 使用邻接列表示图
graph = defaultdict(list) # 例如: graph['A'] = ['B', 'C']
graph['B'] = ['D', 'E']
graph['C'] = ['F']
graph['D'] = []
graph['E'] = ['F']
graph['F'] = []
# 开始从'A'节点进行深度优先遍历
dfs(graph, 'A')
```
这个代码会按照“深”然后“广”的顺序访问图中的节点。如果你想要返回遍历的路径,而不是简单的打印,你可以稍微修改一下代码。
阅读全文