广度优先遍历与最短路径
系统讲解借助 FIFO 队列实现的图广度优先遍历(BFS)、无权图最短距离数组 ord[] 与最短路径还原,并重点剖析 Java LinkedList 误用 push/pop 退化为 LIFO 栈的经典陷阱。
学完这一章,你能够
- 系统讲解借助 FIFO 队列实现的图广度优先遍历(BFS)、无权图最短距离数组 ord[] 与最短路径还原,并重点剖析 Java LinkedList 误用 push/pop 退化为 LIFO 栈的经典陷阱。
广度优先遍历(BFS)三步骤与无权最短路径性质
图的广度优先遍历(Breadth-First Search,BFS)从源点 `s` 出发按距离由近及远逐层扩散,可分为三个标准步骤:(1)初始化先进先出(FIFO)辅助队列 `q`,将起点入队并立即标记 `visited[s] = true`;(2)当队列非空时,从队首取出顶点 `v`,遍历其所有未访问邻接点 `i`,逐一标记已访问并追加至队尾;(3)当队列为空时,所有与起点连通的顶点均已按距源点的最少边数顺序访问完毕。正因为节点严格按层距(0 跳、1 跳、2 跳……)展开,BFS 天然求出无权图从源点到所有可达顶点的最短路径。
ord 最短距离数组与 FIFO 队列关键实现陷阱
在寻路类的基础上新增整型数组 `ord[]`(初始化为 `-1`、起点置 `ord[s] = 0`),每次通过边 `(v, i)` 首次发现未访问顶点 `i` 时同步记录 `from[i] = v` 与 `ord[i] = ord[v] + 1`。查询最短路径长度的 `length(w)` 直接返回 `ord[w]`(若 `w` 不可达则返回 `-1`)。基于邻接表时 BFS 时间复杂度为 O(V + E),基于邻接矩阵时为 O(V^2)。
工程实现中必须特别警惕一个常见队列 API 陷阱:参考 Java 代码 `ShortestPath.java` 在使用 `LinkedList<Integer>` 时调用了 `q.push(i)` 与 `q.pop()`,但在 Java `Deque` 规范中 `push`/`pop` 操作的是链表**同一端(表头)**,等价于后进先出(LIFO)栈而非 FIFO 队列,会导致算法退化为深度优先探索并丧失无权图最短路径保证!正确的 Java 队列写法应为 `q.add(i)`/`q.offer(i)` 搭配 `q.remove()`/`q.poll()`(Python 中为 `deque.append` 搭配 `deque.popleft`)。本站离线 Python 实验脚本已同时验证了标准 FIFO BFS 最短路径、含捷径图上 BFS 优于 DFS 的实测对比,以及误用 LIFO 栈破坏最短距离的反例。
离线校验 FIFO 广度优先无权图最短路径、ord 距离数组与 LIFO 栈陷阱反例
展开查看收起
"""Offline algorithm verification lab for Chapter 44 (graph-theory-short-path)."""
from collections import deque
import json
VERSION = "CPython 3.12.14 offline DSA verifier (graph-theory-short-path)"
class SparseGraph:
def __init__(self, n: int):
self.n = n
self.g = [[] for _ in range(n)]
def V(self) -> int:
return self.n
def add_edge(self, v: int, w: int) -> None:
self.g[v].append(w)
if v != w:
self.g[w].append(v)
def has_edge(self, v: int, w: int) -> bool:
return w in self.g[v]
def adj(self, v: int):
return self.g[v]
class ShortestPathBFS:
"""True FIFO-queue BFS for unweighted shortest path and distance ord[]."""
def __init__(self, graph: SparseGraph, s: int):
assert 0 <= s < graph.V()
self.G = graph
self.s = s
self.visited = [False] * graph.V()
self.frm = [-1] * graph.V()
self.ord = [-1] * graph.V()
self.visit_order = []
q = deque()
q.append(s)
self.visited[s] = True
self.ord[s] = 0
while q:
v = q.popleft()
self.visit_order.append(v)
for i in self.G.adj(v):
if not self.visited[i]:
q.append(i)
self.visited[i] = True
self.frm[i] = v
self.ord[i] = self.ord[v] + 1
def has_path(self, w: int) -> bool:
assert 0 <= w < self.G.V()
return self.visited[w]
def path(self, w: int) -> list:
assert self.has_path(w)
stack = []
p = w
while p != -1:
stack.append(p)
p = self.frm[p]
stack.reverse()
return stack
def length(self, w: int) -> int:
assert 0 <= w < self.G.V()
return self.ord[w]
def case_bfs_shortest_path_and_ord():
# 9-vertex graph: component {0..6}, disconnected {7, 8}
g = SparseGraph(9)
for u, v in [(0, 1), (0, 2), (0, 5), (0, 6), (5, 3), (5, 4), (3, 4), (4, 6), (7, 8)]:
g.add_edge(u, v)
bfs = ShortestPathBFS(g, 0)
expected = {
"visit_order": [0, 1, 2, 5, 6, 3, 4],
"ord_0_to_6": [0, 1, 1, 2, 2, 1, 1],
"length_6": 1,
"path_6": [0, 6],
"length_4": 2,
"path_4": [0, 5, 4],
"length_unreachable_7": -1,
"has_path_7": False,
}
actual = {
"visit_order": bfs.visit_order,
"ord_0_to_6": bfs.ord[:7],
"length_6": bfs.length(6),
"path_6": bfs.path(6),
"length_4": bfs.length(4),
"path_4": bfs.path(4),
"length_unreachable_7": bfs.length(7),
"has_path_7": bfs.has_path(7),
}
return {
"name": "bfs_shortest_path_and_ord",
"summary": "验证 FIFO 队列广度优先遍历的层级访问次序、ord 最短距离数组及不可达节点返回 -1",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bfs_shortest_vs_dfs_non_shortest():
# Graph where 0-1-2-3-4-5 is explored first by DFS, while direct shortcut 0-5 has length 1
g = SparseGraph(6)
for u, v in [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (0, 5)]:
g.add_edge(u, v)
# DFS path from 0 to 5
visited = [False] * 6
frm = [-1] * 6
def dfs(v):
visited[v] = True
for i in g.adj(v):
if not visited[i]:
frm[i] = v
dfs(i)
dfs(0)
dfs_path = []
cur = 5
while cur != -1:
dfs_path.append(cur)
cur = frm[cur]
dfs_path.reverse()
bfs = ShortestPathBFS(g, 0)
bfs_path = bfs.path(5)
expected = {
"dfs_path_to_5": [0, 1, 2, 3, 4, 5],
"dfs_hops": 5,
"bfs_path_to_5": [0, 5],
"bfs_hops": 1,
"bfs_strictly_shorter": True,
}
actual = {
"dfs_path_to_5": dfs_path,
"dfs_hops": len(dfs_path) - 1,
"bfs_path_to_5": bfs_path,
"bfs_hops": bfs.length(5),
"bfs_strictly_shorter": bfs.length(5) < (len(dfs_path) - 1),
}
return {
"name": "bfs_shortest_vs_dfs_non_shortest",
"summary": "在含捷径边 (0,5) 的图上对比 DFS 路径(5 跳)与 BFS 最短路径(1 跳),验证无权图 BFS 最优性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fifo_queue_vs_lifo_stack_pitfall():
# Demonstrates why Java LinkedList.push()/pop() (LIFO stack!) breaks BFS shortest-path optimality
# Graph: 0 connects to 1 and 2; 1 connects to 3; 2 connects to 4; 4 connects to 3
# Shortest distance from 0 to 3 is 2 via 0->1->3.
# If a LIFO stack pushes 1 then 2, it pops 2 first, explores 4, then visits 3 with ord=3!
g = SparseGraph(5)
for u, v in [(0, 1), (0, 2), (1, 3), (2, 4), (4, 3)]:
g.add_edge(u, v)
# True FIFO queue BFS
bfs = ShortestPathBFS(g, 0)
# Buggy LIFO stack (simulating Java LinkedList.push/pop)
vis = [False] * 5
ord_lifo = [-1] * 5
stack = [0]
vis[0] = True
ord_lifo[0] = 0
while stack:
v = stack.pop() # LIFO pop!
for i in g.adj(v):
if not vis[i]:
stack.append(i)
vis[i] = True
ord_lifo[i] = ord_lifo[v] + 1
expected = {
"fifo_bfs_dist_to_3": 2,
"fifo_bfs_path_to_3": [0, 1, 3],
"lifo_bug_dist_to_3": 3,
"lifo_violates_shortest_path": True,
}
actual = {
"fifo_bfs_dist_to_3": bfs.length(3),
"fifo_bfs_path_to_3": bfs.path(3),
"lifo_bug_dist_to_3": ord_lifo[3],
"lifo_violates_shortest_path": ord_lifo[3] > bfs.length(3),
}
return {
"name": "fifo_queue_vs_lifo_stack_pitfall",
"summary": "实测对比标准 FIFO 队列(add/remove)与误用 LIFO 栈(push/pop)的差异,证明 LIFO 会破坏无权图最短路径性质",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_bfs_shortest_path_and_ord(),
case_bfs_shortest_vs_dfs_non_shortest(),
case_fifo_queue_vs_lifo_stack_pitfall(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
同一层的多个顶点可能共同连接到下一层的同一个未访问顶点 `x`;如果等到出队才标记,在 `x` 出队之前会被多个前驱重复推入队列,不仅浪费队列空间和重复计算,还可能被后续更晚路径覆盖 `from[x]` 与 `ord[x]`。