图论 · 广度优先搜索与最短路径
用邻接表建模关系网络,掌握队列驱动的 BFS 无权最短路与堆优化的 Dijkstra 正权最短路。
如何用代码表示一张图
图(Graph)由节点(Vertex)和连接节点的边(Edge)组成。在 Python 中,最简洁高效的图建模方式就是用字典表示邻接表:
python
graph = {
"start": ["a", "b"],
"a": ["fin"],
"b": ["a", "fin"],
"fin": [],
}
广度优先搜索(BFS)与队列
广度优先搜索(Breadth-First Search)像水波一样从起点逐层向外扩散:先检查一度关系,再检查二度关系。正因为按层推进,BFS 首次到达目标时找到的一定是边数最少的最短路径。
python
from collections import deque
def bfs_shortest_path(graph: dict[str, list[str]], start: str, goal: str) -> list[str] | None:
queue = deque([[start]])
visited = {start}
while queue:
path = queue.popleft()
node = path[-1]
if node == goal:
return path
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(path + [neighbor])
return None
时间复杂度为 O(V + E)(每个顶点入队一次、每条边检查一次)。务必维护 visited 集合,否则遇到环图会陷入死循环。
带权图:Dijkstra 算法
如果每条边有不同的通行耗时(正权重),BFS 就不适用了,需要改用 Dijkstra 算法:使用最小堆(heapq)每次弹出当前总开销最小的未确定节点,并对其邻居执行松弛操作(Relaxation)。
python
import heapq
def dijkstra(graph: dict[str, list[tuple[str, int]]], start: str) -> dict[str, int]:
dist = {start: 0}
heap = [(0, start)]
while heap:
cost, u = heapq.heappop(heap)
if cost > dist.get(u, float("inf")):
continue
for v, weight in graph.get(u, []):
new_cost = cost + weight
if new_cost < dist.get(v, float("inf")):
dist[v] = new_cost
heapq.heappush(heap, (new_cost, v))
return dist
BFS vs Dijkstra 速查表
| 算法 | 适用图类型 | 核心数据结构 | 复杂度 |
|---|---|---|---|
| BFS | 无权图(每步代价相同) | 双端队列 deque | O(V + E) |
| Dijkstra | 正权图(无负权边) | 优先队列 heapq | O((V + E) log V) |
| Bellman-Ford | 含负权边的图 | 边松弛循环 | O(V · E) |