在图论算法中,图的遍历是基础且重要的操作,主要有深度优先搜索(DFS)和广度优先搜索(BFS)。
深度优先搜索类似走迷宫,尽可能深地探索每个分支。以 Python 实现无向图的 DFS 为例:
python
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}visited = set()def dfs(node):
if node not in visited:
print(node)
visited.add(node)
for neighbor in graph[node]:
dfs(neighbor)dfs('A')
这里从节点A开始,依次访问其邻居节点,递归进行,直到所有可达节点都被访问。
广度优先搜索则像水波纹一样,一层一层向外扩展。Python 实现 BFS 如下:
python
from collections import dequedef bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)bfs(graph, 'A')
从起始节点A加入队列,每次取出队首节点,访问其邻居节点,未访问过的加入队列。DFS 和 BFS 在路径查找、拓扑排序等场景有广泛应用,掌握它们能解决很多图相关的算法问题。