"""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()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
入口文件:projects/data-structures-graph-theory-short-path-lab/explore-graph-theory-short-path.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-graph-theory-short-path.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2665.zip