Python 标准库与 SQLite 实现 Yen:可重放的 K 条最短无环路径
当系统只需要一条最优路线,最短路通常就够了。但故障切换、备选路由和可解释方案比较经常需要前 K 条路线,而且每条路线都不许重复节点。问题的难点不只是多调用几次 Dijkstra:同一对端点可能有多条真实边,零权边会制造并列,候选不能漏,结果还要能在数据库里的旧图上重放。
本文实现只使用 Python 标准库与 SQLite,以 Yen 的无环路径枚举为主线。所有九段代码均可在 Python 3.11 或更新版本独立运行,运行时不需要安装第三方包。每段下方都是实际执行得到的精确标准输出。本文只处理非负整数权重的有限有向多重图;不会把负权、近似截断或允许回路的问题混在同一承诺里。

Jin Y. Yen 的原论文给出了 K 条最短无环路径的偏离式枚举思路。本文将路径身份细化为原始边 ID 序列,并明确补上可复现的并列规则。NetworkX 官方 shortest_simple_paths 文档指出其接口不接受 MultiGraph 或 MultiDiGraph,所以这里不能只换成一个库调用再假设平行边已被正确处理。
一、先把图与路径身份写进契约
这里的输入是有限有向多重图:同一对端点允许出现多条边,每条边都有唯一、非空的原始字符串 ID。路径是否相同由边 ID 序列决定,节点序列相同并不意味着是同一条路径。我们要求节点不重复,因此自环与来回绕圈都不能出现在答案中;起点等于终点时,只返回零条边的空路径。节点必须显式登记,孤立节点不能因为没有边而从快照里消失。
边权限定为 Python 的非负整数,而且明确拒绝布尔值。原因不是布尔值不能相加,而是 True 是 int 的子类,悄悄接受它会把上游字段错误伪装成权重一。整数避免浮点近似让排序、去重和重放产生不同结论。下面同时保留平行边,并展示三种应当在入口拒绝的输入。此后各段均可单独保存为 Python 文件运行;为了独立复制使用,共用定义会完整重复。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
g = graph(("S", "T"), [("p1", "S", "T", 2), ("p2", "S", "T", 2)])
print([e.id for e in g[1]])
for weight in (-1, True, 1.5):
try:
graph(("S", "T"), [("x", "S", "T", weight)])
except ValueError as exc:
print(type(weight).__name__ + ": " + str(exc))
try:
graph(("S", "T"), [("x", "S", "T", 1), ("x", "S", "T", 2)])
except ValueError as exc:
print(exc)精确输出:
['p1', 'p2'] int: weight must be a nonnegative int bool: weight must be a nonnegative int float: weight must be a nonnegative int edge IDs must be unique nonempty strings
图构造函数将边冻结为元组,将邻接表包成只读映射。算法对图只读,临时禁用项通过参数传入;这样不会在一次支路搜索失败后忘记恢复原图。节点和边 ID 均按 Python 字符串顺序比较,没有自然数字排序,也不做大小写折叠或 Unicode 归一化。若业务需要另一种规则,应当在接入层先生成稳定 ID,并给规则独立版本。
二、同权路径也必须有唯一且可复现的顺序
仅写按总权重排序还不够:零权边、平行边和等价路线都可能造成大量并列。本文的总排序键依次为总权重、边数、边 ID 元组。边数是明确的第二目标,不能在文档里省略。这意味着同权时更少跳数的路径先出现,再按边 ID 序列的字典序排列;它不是只按权重与 ID 的另一种契约。
第二项还有算法意义。沿任何边扩展,权重不会下降,而边数严格增加;所以即使存在零权环,重复节点的绕圈路线也不可能改善该节点的最优标签。相同前缀拼接到两个支路上,不改变两个支路的相对顺序:共同成本和共同边数同时相加,共同 ID 前缀同时放到元组前面。因此用于选支路的排序与最终候选池的排序完全一致。
from dataclasses import dataclass
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
paths = [
Path(2, ("S", "A", "T"), ("a", "b")),
Path(1, ("S", "T"), ("z",)),
Path(2, ("S", "T"), ("r2",)),
Path(2, ("S", "T"), ("r10",)),
]
for p in sorted(paths, key=Path.rank):
print(p.rank())精确输出:
(1, 1, ('z',))
(2, 1, ('r10',))
(2, 1, ('r2',))
(2, 2, ('a', 'b'))注意 r10 排在 r2 之前,这正是字符串字典序。不要使用数据库返回行的先后、集合遍历次序或堆里的临时计数器充当业务排序;那些技巧可以消除比较异常,却不能替代一个跨进程可重放的排序契约。Python 的 heapq 官方文档说明了最小堆与比较行为,本文只使用已有多年的 heappush、heappop 接口。
三、两种临时封锁必须分清作用范围
Yen 将一条已接纳路径拆成根前缀和支路。根前缀已经走过的节点必须禁止支路再次进入,但支路起点本身不能封锁。另一方面,为了避开已经接纳的相同根前缀,需要封锁它们紧随此前缀的那一条原始边。两种封锁都仅在本次支路最短路调用中生效,不写入图,不累计到下一处分叉。
多重图最容易错在把边封锁写成端点对。删除 S 到 A 的某条边,不能顺手删除同端点的另一条平行边。下面先从 A 搜索,观察返回 S 的便宜绕行在封锁根节点 S 后消失;再从 S 搜索,只禁用 sa1 时,sa2 仍然存在。最短支路内部沿用带确定性标签的 Dijkstra,但这只是 Yen 的子程序,不负责枚举整个候选空间。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
def shortest(g, source, target, blocked_nodes=frozenset(),
blocked_edges=frozenset()):
ns, es, adj = g
if source in blocked_nodes or target in blocked_nodes:
return None
initial = (0, 0, ())
best = {source: initial}
heap = [(initial, source, (source,))]
while heap:
rank, u, nodes = heappop(heap)
if best.get(u) != rank:
continue
cost, hops, ids = rank
if u == target:
return Path(cost, nodes, ids)
for e in adj[u]:
if e.id in blocked_edges or e.v in blocked_nodes:
continue
new_rank = (cost + e.w, hops + 1, ids + (e.id,))
if e.v not in best or new_rank < best[e.v]:
best[e.v] = new_rank
heappush(heap, (new_rank, e.v, nodes + (e.v,)))
return None
g = graph(("S", "A", "B", "T"), [
("sa1", "S", "A", 0), ("sa2", "S", "A", 0),
("as", "A", "S", 0), ("sb", "S", "B", 0),
("bt", "B", "T", 0), ("at", "A", "T", 2)
])
p = shortest(g, "A", "T")
print("no root block:", p.cost, p.ids)
p = shortest(g, "A", "T", frozenset({"S"}))
print("root S blocked:", p.cost, p.ids)
p = shortest(g, "S", "T", blocked_edges=frozenset({"sa1", "sb"}))
print("only sa1 removed:", p.cost, p.ids)精确输出:
no root block: 0 ('as', 'sb', 'bt')
root S blocked: 2 ('at',)
only sa1 removed: 2 ('sa2', 'at')这里不在最短路松弛中额外记录每个状态的访问集合。非负权重与优先最少边数保证最优支路本身不会含环;根前缀的节点封锁再保证拼接后的整条路径无环。若换成负权、依赖历史节点的成本或其他不保持前缀顺序的评分,这个证明不再成立,不能原样复用。
四、完整 Yen:保留所有尚未选中的候选
下面给出完整实现。accepted 保存已按序输出的路径,candidates 是跨轮保留的最小堆,seen 保存已经生成的完整边 ID 序列。每次只展开最新接纳路径的每个分叉位置,但旧候选一直留在堆中等待比较。每个位置都要检查全部已接纳路径,而不是仅检查上一条路径;否则相同根前缀很容易再生成旧答案,或在不正确的去重处理下漏掉下一条答案。
多重图中的相同根前缀,必须比较原始边 ID 前缀。假如两条路线都经过 S、A,但分别使用 sa1 与 sa2,它们在边路径意义下已经分叉。示例中的零权往返边 ab、ba 可以存在于图中,但最终任何答案都不能重复节点。输出的前两条具有相同节点序列,因其原始边不同而都应保留。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
def shortest(g, source, target, blocked_nodes=frozenset(),
blocked_edges=frozenset()):
ns, es, adj = g
if source in blocked_nodes or target in blocked_nodes:
return None
initial = (0, 0, ())
best = {source: initial}
heap = [(initial, source, (source,))]
while heap:
rank, u, nodes = heappop(heap)
if best.get(u) != rank:
continue
cost, hops, ids = rank
if u == target:
return Path(cost, nodes, ids)
for e in adj[u]:
if e.id in blocked_edges or e.v in blocked_nodes:
continue
new_rank = (cost + e.w, hops + 1, ids + (e.id,))
if e.v not in best or new_rank < best[e.v]:
best[e.v] = new_rank
heappush(heap, (new_rank, e.v, nodes + (e.v,)))
return None
def yen(g, source, target):
if source not in g[0] or target not in g[0]:
raise ValueError("unknown source or target")
first = shortest(g, source, target)
if first is None:
return
accepted = [first]
seen = {first.ids}
candidates = []
weights = {e.id: e.w for e in g[1]}
yield first
while True:
previous = accepted[-1]
root_cost = 0
for i in range(len(previous.ids)):
root_ids = previous.ids[:i]
root_nodes = previous.nodes[:i + 1]
blocked_edges = {
p.ids[i] for p in accepted
if len(p.ids) > i and p.ids[:i] == root_ids
}
spur = shortest(
g, root_nodes[-1], target,
frozenset(root_nodes[:-1]), frozenset(blocked_edges)
)
if spur is not None:
ids = root_ids + spur.ids
if ids not in seen:
path = Path(root_cost + spur.cost,
root_nodes[:-1] + spur.nodes, ids)
seen.add(ids)
heappush(candidates, (path.rank(), path.nodes))
root_cost += weights[previous.ids[i]]
if not candidates:
return
rank, nodes = heappop(candidates)
path = Path(rank[0], nodes, rank[2])
accepted.append(path)
yield path
def query(g, source, target, requested_k):
if type(requested_k) is not int or requested_k < 1:
raise ValueError("requested_k must be a positive int")
found = []
for path in yen(g, source, target):
found.append(path)
if len(found) > requested_k:
break
return found[:requested_k], len(found) <= requested_k
g = graph(("S", "A", "B", "T"), [
("sa1", "S", "A", 0), ("sa2", "S", "A", 0),
("sb", "S", "B", 0), ("ab", "A", "B", 0),
("ba", "B", "A", 0), ("at", "A", "T", 1),
("bt", "B", "T", 1), ("st", "S", "T", 2)
])
for number, p in enumerate(yen(g, "S", "T"), 1):
print(number, p.cost, len(p.ids), ",".join(p.ids))精确输出:
1 1 2 sa1,at 2 1 2 sa2,at 3 1 2 sb,bt 4 1 3 sa1,ab,bt 5 1 3 sa2,ab,bt 6 1 3 sb,ba,at 7 2 1 st
seen 同时覆盖已接纳和待选候选,只有首次生成的 ID 序列入堆。相同路径即使在不同分叉处再次产生,也不改变其权重或排序位置,因此可安全去重。这里保留候选池的全部条目以便审计;没有加入任意 beam 宽度、候选总数阈值或每层只取若干路线的近似裁剪。
五、候选池不是每一轮重新开始的临时列表
一轮展开可能产生成本三和成本八的候选,其中成本三先被接纳。下一轮新出现的候选成本十,并不意味着下一条答案就是十,因为上一轮的成本八仍在等待。把候选堆在循环开头清空,是一种看似合理、实际会打乱完整顺序的错误。下面的小例子只抽出候选池这一部件,展示跨轮保留和按边序列去重。
不要用节点序列作为去重键:示例中 p1 与 p2 具有同一节点序列,但代表不同原始边;两条都应留在候选池。也不要把发现顺序当成并列规则。最小堆保存的是完整排序键,候选发现时间只是实现细节。
from dataclasses import dataclass
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
from heapq import heappop, heappush
heap, seen = [], set()
def offer(p):
if p.ids not in seen:
seen.add(p.ids)
heappush(heap, (p.rank(), p.nodes))
offer(Path(3, ("S", "T"), ("p1",)))
offer(Path(8, ("S", "T"), ("p2",)))
offer(Path(3, ("S", "T"), ("p1",)))
print("round 1:", heappop(heap)[0])
offer(Path(10, ("S", "T"), ("p3",)))
print("round 2:", heappop(heap)[0])
print("still waiting:", heappop(heap)[0])精确输出:
round 1: (3, 1, ('p1',))
round 2: (8, 1, ('p2',))
still waiting: (10, 1, ('p3',))Yen 的关键是不遗漏尚未接纳路径能够产生的最优偏离。根前缀封锁让偏离满足无环要求,下一条边封锁让它避开已接纳前缀分支,持续存在的候选池负责比较各分支当前最优项。对新接纳路径继续展开,才会暴露同一分支更后面的候选。这个过程与先求若干条允许绕圈的 walk 再过滤不同:零权环可能制造大量无用 walk,预先限制其数量也不能保证得到所需简单路径。
六、requestedK 已满足,不等于图中路径已枚举完
接口同时返回路径列表与 complete 标志。这里 complete 的含义非常严格:返回的列表已经包含该快照下从起点到终点的所有节点简单边路径。请求三条并得到三条,只能说明配额满足,不能说明不存在第四条。为准确判断,query 会读取最多 requestedK 加一条;第 K 加一条只是探针,不计入返回列表。
当总数恰好等于 requestedK,探针会继续展开最后一条路径直到确认候选池为空,随后 complete 才是 True。这有额外计算成本,却避免把列表长度等于 K 错写成完整。若生产接口不愿支付探针成本,可以返回 exhaustionUnknown 等独立状态;不能把未检查伪装成已穷尽。本例接受正整数 K,拒绝零、负数和布尔值。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
def shortest(g, source, target, blocked_nodes=frozenset(),
blocked_edges=frozenset()):
ns, es, adj = g
if source in blocked_nodes or target in blocked_nodes:
return None
initial = (0, 0, ())
best = {source: initial}
heap = [(initial, source, (source,))]
while heap:
rank, u, nodes = heappop(heap)
if best.get(u) != rank:
continue
cost, hops, ids = rank
if u == target:
return Path(cost, nodes, ids)
for e in adj[u]:
if e.id in blocked_edges or e.v in blocked_nodes:
continue
new_rank = (cost + e.w, hops + 1, ids + (e.id,))
if e.v not in best or new_rank < best[e.v]:
best[e.v] = new_rank
heappush(heap, (new_rank, e.v, nodes + (e.v,)))
return None
def yen(g, source, target):
if source not in g[0] or target not in g[0]:
raise ValueError("unknown source or target")
first = shortest(g, source, target)
if first is None:
return
accepted = [first]
seen = {first.ids}
candidates = []
weights = {e.id: e.w for e in g[1]}
yield first
while True:
previous = accepted[-1]
root_cost = 0
for i in range(len(previous.ids)):
root_ids = previous.ids[:i]
root_nodes = previous.nodes[:i + 1]
blocked_edges = {
p.ids[i] for p in accepted
if len(p.ids) > i and p.ids[:i] == root_ids
}
spur = shortest(
g, root_nodes[-1], target,
frozenset(root_nodes[:-1]), frozenset(blocked_edges)
)
if spur is not None:
ids = root_ids + spur.ids
if ids not in seen:
path = Path(root_cost + spur.cost,
root_nodes[:-1] + spur.nodes, ids)
seen.add(ids)
heappush(candidates, (path.rank(), path.nodes))
root_cost += weights[previous.ids[i]]
if not candidates:
return
rank, nodes = heappop(candidates)
path = Path(rank[0], nodes, rank[2])
accepted.append(path)
yield path
def query(g, source, target, requested_k):
if type(requested_k) is not int or requested_k < 1:
raise ValueError("requested_k must be a positive int")
found = []
for path in yen(g, source, target):
found.append(path)
if len(found) > requested_k:
break
return found[:requested_k], len(found) <= requested_k
g = graph(("S", "A", "B", "T"), [
("sa1", "S", "A", 0), ("sa2", "S", "A", 0),
("sb", "S", "B", 0), ("ab", "A", "B", 0),
("ba", "B", "A", 0), ("at", "A", "T", 1),
("bt", "B", "T", 1), ("st", "S", "T", 2)
])
for k in (3, 7, 9):
paths, complete = query(g, "S", "T", k)
print("K=" + str(k), "count=" + str(len(paths)), "complete=" + str(complete))
paths, complete = query(g, "T", "S", 2)
print("unreachable:", len(paths), complete)
paths, complete = query(g, "S", "S", 2)
print("same endpoint:", [(p.cost, p.ids) for p in paths], complete)
for bad in (0, True):
try:
query(g, "S", "T", bad)
except ValueError as exc:
print(exc)
try:
query(g, "missing", "T", 2)
except ValueError as exc:
print(exc)精确输出:
K=3 count=3 complete=False K=7 count=7 complete=True K=9 count=7 complete=True unreachable: 0 True same endpoint: [(0, ())] True requested_k must be a positive int requested_k must be a positive int unknown source or target
不可达是一个已完成的空结果,而未知端点是输入错误,两者不能混为一谈。requestedK 只控制返回规模,不能成为算法正确性的前提。这个实现对于每一个有限 K 都返回严格排序的正确前缀;只有确认没有更多路径时才宣称全集完整。超时或外部取消也不能被折算成 complete=True,生产服务应另设执行状态与预算耗尽原因。
七、SQLite 保存可寻址图快照,而不是当前边表的名字
重放需要同一批节点、边 ID、方向、权重和规则,而不是一个可能已经变更的图名称。这里先把内存图规范化为 UTF-8 字节,按节点及边 ID 固定顺序排列,再以 SHA-256 作为内容地址,整体保存到 SQLite 的 BLOB 列。一次读取一条载荷记录就能恢复这一逻辑快照,避免分别读取可变节点表和边表时混入不同版本。
权重在快照里写成十进制字符串,因此不会落入 SQLite 有符号整数存储范围的限制,Python 恢复后仍用任意精度整数计算。十进制字符串转换仍受 Python 运行时的位数安全限制与可用资源限制;遇到极端大整数时应报告转换失败,不能截断或改用浮点数。JSON 的字段次序与分隔符固定;该规范是本实现的格式契约,不声称它是通用 JSON 规范化标准。恢复时既校验内容哈希,也重新编码并比对规范字节,拒绝与当前格式不符的载荷。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
import hashlib
import json
import sqlite3
ALGORITHM = "yen-edge-id-v1"
RANK_CONTRACT = "cost,hops,python-str-edge-id-tuple-v1"
def encode(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True,
separators=(",", ":")).encode("utf-8")
def snapshot_bytes(g):
return encode({"format": "directed-multigraph-v1",
"nodes": list(g[0]),
"edges": [[e.id, e.u, e.v, str(e.w)] for e in g[1]]})
def open_db():
db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE snapshots (
id TEXT PRIMARY KEY,
payload BLOB NOT NULL
);
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
snapshot_id TEXT NOT NULL REFERENCES snapshots(id),
request BLOB NOT NULL,
result BLOB NOT NULL
);
""")
return db
def save_snapshot(db, g):
payload = snapshot_bytes(g)
sid = hashlib.sha256(payload).hexdigest()
with db:
db.execute("INSERT OR IGNORE INTO snapshots VALUES (?, ?)",
(sid, payload))
stored = db.execute("SELECT payload FROM snapshots WHERE id=?",
(sid,)).fetchone()[0]
if stored != payload:
raise ValueError("snapshot ID collision or tampering")
return sid
def load_snapshot(db, sid):
row = db.execute("SELECT payload FROM snapshots WHERE id=?",
(sid,)).fetchone()
if row is None:
raise ValueError("unknown snapshot")
payload = row[0]
if hashlib.sha256(payload).hexdigest() != sid:
raise ValueError("snapshot hash mismatch")
data = json.loads(payload)
if data["format"] != "directed-multigraph-v1":
raise ValueError("unknown snapshot format")
g = graph(data["nodes"],
[(eid, u, v, int(w)) for eid, u, v, w in data["edges"]])
if snapshot_bytes(g) != payload:
raise ValueError("noncanonical snapshot")
return g
g1 = graph(("T", "S", "I"), [
("b", "S", "T", 2 ** 80), ("a", "S", "T", 0)
])
g2 = graph(("I", "S", "T"), [
("a", "S", "T", 0), ("b", "S", "T", 2 ** 80)
])
db = open_db()
sid1, sid2 = save_snapshot(db, g1), save_snapshot(db, g2)
restored = load_snapshot(db, sid1)
print("same ID:", sid1 == sid2)
print("nodes:", restored[0])
print("large weight:", restored[1][1].w)
print("stored rows:", db.execute("SELECT count(*) FROM snapshots").fetchone()[0])
db.close()精确输出:
same ID: True
nodes: ('I', 'S', 'T')
large weight: 1208925819614629174706176
stored rows: 1哈希是重放完整性检查,不是权限控制或数字签名。若有人能同时替换载荷、内容地址和运行记录,数据库本身无法证明来源可信;需要另行保存可信的快照地址或签名。运行请求与结果本身未认证;若修改请求后仍得到相同结果,重放也不会报警。数据库也没有因为表名叫 snapshots 就自动只读,应用与运维仍应限制更新和删除。SQLite 的隔离文档讨论事务中的读取一致性;本文的持久逻辑快照与数据库引擎的事务快照是两个不同层次。
八、把请求、版本与结果一起记录,再重新执行核对
下面保存四类审计信息:图内容地址、源与目标及 requestedK、算法和排序契约版本、实际输出及完整性标志。重放不是把旧结果再显示一次,而是从对应快照重新求解,并逐字节比较规范输出。成本同样保存为十进制字符串,原始边 ID、节点序列和 complete 都在比对范围内。
示例创建第二个图快照时,旧运行仍然使用旧内容地址,所以不会悄悄切到当前图。最后故意篡改快照载荷,展示哈希校验如何让错误显式失败。SQLite 外键在每个新连接上显式启用;写入快照和运行记录各自放在事务中。演示使用内存库以便独立执行,在实际归档时将连接目标换成文件路径,并制定文件备份、保存期限与并发策略。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
def shortest(g, source, target, blocked_nodes=frozenset(),
blocked_edges=frozenset()):
ns, es, adj = g
if source in blocked_nodes or target in blocked_nodes:
return None
initial = (0, 0, ())
best = {source: initial}
heap = [(initial, source, (source,))]
while heap:
rank, u, nodes = heappop(heap)
if best.get(u) != rank:
continue
cost, hops, ids = rank
if u == target:
return Path(cost, nodes, ids)
for e in adj[u]:
if e.id in blocked_edges or e.v in blocked_nodes:
continue
new_rank = (cost + e.w, hops + 1, ids + (e.id,))
if e.v not in best or new_rank < best[e.v]:
best[e.v] = new_rank
heappush(heap, (new_rank, e.v, nodes + (e.v,)))
return None
def yen(g, source, target):
if source not in g[0] or target not in g[0]:
raise ValueError("unknown source or target")
first = shortest(g, source, target)
if first is None:
return
accepted = [first]
seen = {first.ids}
candidates = []
weights = {e.id: e.w for e in g[1]}
yield first
while True:
previous = accepted[-1]
root_cost = 0
for i in range(len(previous.ids)):
root_ids = previous.ids[:i]
root_nodes = previous.nodes[:i + 1]
blocked_edges = {
p.ids[i] for p in accepted
if len(p.ids) > i and p.ids[:i] == root_ids
}
spur = shortest(
g, root_nodes[-1], target,
frozenset(root_nodes[:-1]), frozenset(blocked_edges)
)
if spur is not None:
ids = root_ids + spur.ids
if ids not in seen:
path = Path(root_cost + spur.cost,
root_nodes[:-1] + spur.nodes, ids)
seen.add(ids)
heappush(candidates, (path.rank(), path.nodes))
root_cost += weights[previous.ids[i]]
if not candidates:
return
rank, nodes = heappop(candidates)
path = Path(rank[0], nodes, rank[2])
accepted.append(path)
yield path
def query(g, source, target, requested_k):
if type(requested_k) is not int or requested_k < 1:
raise ValueError("requested_k must be a positive int")
found = []
for path in yen(g, source, target):
found.append(path)
if len(found) > requested_k:
break
return found[:requested_k], len(found) <= requested_k
import hashlib
import json
import sqlite3
ALGORITHM = "yen-edge-id-v1"
RANK_CONTRACT = "cost,hops,python-str-edge-id-tuple-v1"
def encode(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True,
separators=(",", ":")).encode("utf-8")
def snapshot_bytes(g):
return encode({"format": "directed-multigraph-v1",
"nodes": list(g[0]),
"edges": [[e.id, e.u, e.v, str(e.w)] for e in g[1]]})
def open_db():
db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE snapshots (
id TEXT PRIMARY KEY,
payload BLOB NOT NULL
);
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
snapshot_id TEXT NOT NULL REFERENCES snapshots(id),
request BLOB NOT NULL,
result BLOB NOT NULL
);
""")
return db
def save_snapshot(db, g):
payload = snapshot_bytes(g)
sid = hashlib.sha256(payload).hexdigest()
with db:
db.execute("INSERT OR IGNORE INTO snapshots VALUES (?, ?)",
(sid, payload))
stored = db.execute("SELECT payload FROM snapshots WHERE id=?",
(sid,)).fetchone()[0]
if stored != payload:
raise ValueError("snapshot ID collision or tampering")
return sid
def load_snapshot(db, sid):
row = db.execute("SELECT payload FROM snapshots WHERE id=?",
(sid,)).fetchone()
if row is None:
raise ValueError("unknown snapshot")
payload = row[0]
if hashlib.sha256(payload).hexdigest() != sid:
raise ValueError("snapshot hash mismatch")
data = json.loads(payload)
if data["format"] != "directed-multigraph-v1":
raise ValueError("unknown snapshot format")
g = graph(data["nodes"],
[(eid, u, v, int(w)) for eid, u, v, w in data["edges"]])
if snapshot_bytes(g) != payload:
raise ValueError("noncanonical snapshot")
return g
def result_bytes(paths, complete):
return encode({"complete": complete,
"paths": [{"cost": str(p.cost), "nodes": list(p.nodes),
"edge_ids": list(p.ids)} for p in paths]})
def record_run(db, sid, source, target, requested_k):
g = load_snapshot(db, sid)
paths, complete = query(g, source, target, requested_k)
request = encode({"algorithm": ALGORITHM, "rank": RANK_CONTRACT,
"source": source, "target": target,
"requestedK": requested_k})
result = result_bytes(paths, complete)
with db:
cur = db.execute("INSERT INTO runs(snapshot_id,request,result) "
"VALUES (?,?,?)", (sid, request, result))
return cur.lastrowid
def replay(db, run_id):
row = db.execute("SELECT snapshot_id,request,result FROM runs WHERE id=?",
(run_id,)).fetchone()
if row is None:
raise ValueError("unknown run")
sid, raw_request, expected = row
req = json.loads(raw_request)
if req["algorithm"] != ALGORITHM or req["rank"] != RANK_CONTRACT:
raise ValueError("unsupported replay contract")
paths, complete = query(load_snapshot(db, sid), req["source"],
req["target"], req["requestedK"])
return result_bytes(paths, complete) == expected
g = graph(("S", "A", "B", "T"), [
("sa1", "S", "A", 0), ("sa2", "S", "A", 0),
("sb", "S", "B", 0), ("ab", "A", "B", 0),
("ba", "B", "A", 0), ("at", "A", "T", 1),
("bt", "B", "T", 1), ("st", "S", "T", 2)
])
db = open_db()
sid = save_snapshot(db, g)
run_id = record_run(db, sid, "S", "T", 3)
print("replay:", replay(db, run_id))
changed = graph(g[0], [(e.id, e.u, e.v, e.w + 10) for e in g[1]])
print("new snapshot:", save_snapshot(db, changed) != sid)
print("old replay:", replay(db, run_id))
with db:
db.execute("UPDATE snapshots SET payload=? WHERE id=?", (b"{}", sid))
try:
replay(db, run_id)
except ValueError as exc:
print(exc)
db.close()精确输出:
replay: True new snapshot: True old replay: True snapshot hash mismatch
Python sqlite3 官方文档说明连接上下文用于事务提交或回滚,并不负责关闭连接,所以代码最后显式 close。这里使用兼容 Python 3.11 的事务方式,没有依赖较新版本的 autocommit 参数。外键行为可查SQLite 官方外键文档。对于实时更新的业务图,应先在同一数据库读取事务中取全量输入,再冻结为新内容地址;不能逐行从不断变化的在线数据拼出一个号称固定的历史版本。
九、用独立穷举 oracle 检查完整性与确定性
展示七条漂亮结果并不能证明实现正确。小图可以用完全不同的策略验证:深度优先搜索枚举全部节点简单边路径,再按契约一次性排序。这个 oracle 不调用最短路,不使用 Yen 的分叉封锁,也没有候选堆,因此能发现两套实现之间的差异。它虽然只适合小图,却很适合自动回归。
下面穷举三个节点上每条有向非自环边的三种状态:不存在、权重零、权重一,总计七百二十九张图。每张图再检查所有九组有序端点,共六千五百六十一组查询。最后单独检查带平行边、零权环和同权路径的样本,并对多个 K 比较正确前缀与 complete。这个规模有限,不能代替正确性证明,但明显强于只断言成本非递减。
from dataclasses import dataclass
from heapq import heappop, heappush
from types import MappingProxyType
@dataclass(frozen=True)
class Edge:
id: str
u: str
v: str
w: int
@dataclass(frozen=True)
class Path:
cost: int
nodes: tuple
ids: tuple
def rank(self):
return self.cost, len(self.ids), self.ids
def graph(nodes, rows):
ns = tuple(nodes)
if any(type(n) is not str or not n for n in ns):
raise ValueError("nodes must be nonempty strings")
if len(set(ns)) != len(ns):
raise ValueError("duplicate node")
ns = tuple(sorted(ns))
es, seen = [], set()
for eid, u, v, w in rows:
if type(eid) is not str or not eid or eid in seen:
raise ValueError("edge IDs must be unique nonempty strings")
if u not in ns or v not in ns:
raise ValueError("unknown endpoint")
if type(w) is not int or w < 0:
raise ValueError("weight must be a nonnegative int")
seen.add(eid)
es.append(Edge(eid, u, v, w))
es = tuple(sorted(es, key=lambda e: e.id))
adj = {n: tuple(e for e in es if e.u == n) for n in ns}
return ns, es, MappingProxyType(adj)
def shortest(g, source, target, blocked_nodes=frozenset(),
blocked_edges=frozenset()):
ns, es, adj = g
if source in blocked_nodes or target in blocked_nodes:
return None
initial = (0, 0, ())
best = {source: initial}
heap = [(initial, source, (source,))]
while heap:
rank, u, nodes = heappop(heap)
if best.get(u) != rank:
continue
cost, hops, ids = rank
if u == target:
return Path(cost, nodes, ids)
for e in adj[u]:
if e.id in blocked_edges or e.v in blocked_nodes:
continue
new_rank = (cost + e.w, hops + 1, ids + (e.id,))
if e.v not in best or new_rank < best[e.v]:
best[e.v] = new_rank
heappush(heap, (new_rank, e.v, nodes + (e.v,)))
return None
def yen(g, source, target):
if source not in g[0] or target not in g[0]:
raise ValueError("unknown source or target")
first = shortest(g, source, target)
if first is None:
return
accepted = [first]
seen = {first.ids}
candidates = []
weights = {e.id: e.w for e in g[1]}
yield first
while True:
previous = accepted[-1]
root_cost = 0
for i in range(len(previous.ids)):
root_ids = previous.ids[:i]
root_nodes = previous.nodes[:i + 1]
blocked_edges = {
p.ids[i] for p in accepted
if len(p.ids) > i and p.ids[:i] == root_ids
}
spur = shortest(
g, root_nodes[-1], target,
frozenset(root_nodes[:-1]), frozenset(blocked_edges)
)
if spur is not None:
ids = root_ids + spur.ids
if ids not in seen:
path = Path(root_cost + spur.cost,
root_nodes[:-1] + spur.nodes, ids)
seen.add(ids)
heappush(candidates, (path.rank(), path.nodes))
root_cost += weights[previous.ids[i]]
if not candidates:
return
rank, nodes = heappop(candidates)
path = Path(rank[0], nodes, rank[2])
accepted.append(path)
yield path
def query(g, source, target, requested_k):
if type(requested_k) is not int or requested_k < 1:
raise ValueError("requested_k must be a positive int")
found = []
for path in yen(g, source, target):
found.append(path)
if len(found) > requested_k:
break
return found[:requested_k], len(found) <= requested_k
from itertools import product
def oracle(g, source, target):
result = []
def visit(u, nodes, ids, cost):
if u == target:
result.append(Path(cost, nodes, ids))
return
for e in g[2][u]:
if e.v not in nodes:
visit(e.v, nodes + (e.v,), ids + (e.id,), cost + e.w)
visit(source, (source,), (), 0)
return sorted(result, key=Path.rank)
nodes = ("A", "B", "C")
arcs = [(u, v) for u in nodes for v in nodes if u != v]
checks = 0
for states in product((-1, 0, 1), repeat=len(arcs)):
rows = [("e" + str(i), u, v, state)
for i, ((u, v), state) in enumerate(zip(arcs, states))
if state >= 0]
small = graph(nodes, rows)
for source in nodes:
for target in nodes:
assert list(yen(small, source, target)) == oracle(small, source, target)
checks += 1
print("exhaustive endpoint queries:", checks)
g = graph(("S", "A", "B", "T"), [
("sa1", "S", "A", 0), ("sa2", "S", "A", 0),
("sb", "S", "B", 0), ("ab", "A", "B", 0),
("ba", "B", "A", 0), ("at", "A", "T", 1),
("bt", "B", "T", 1), ("st", "S", "T", 2)
])
expected = oracle(g, "S", "T")
assert list(yen(g, "S", "T")) == expected
for k in (1, 2, 3, 7, 9):
found, complete = query(g, "S", "T", k)
assert found == expected[:k]
assert complete == (len(expected) <= k)
print("multigraph paths:", len(expected))
print("bounded prefix and completeness: OK")精确输出:
exhaustive endpoint queries: 6561 multigraph paths: 7 bounded prefix and completeness: OK
更完整的回归还应改变输入边的排列,检查同一内容地址与同一结果;加入孤立节点、自环、大整数、不同长度但同总成本的路径;篡改运行版本、结果与快照,分别确认失败模式。生产图不适合穷举,应该保留小图 oracle 作为变更防线,同时记录真实请求的快照以便精确复现异常。
为什么这个枚举不会漏,以及性能边界在哪里
可以把尚未输出的简单边路径按与已接纳路径的首次分叉位置划分。对每个根前缀,暂时封锁已接纳路线使用的下一条原始边,再求剩余图上最优支路,就取得该剩余分支当前最好的候选。支路不能访问根前缀的早期节点,所以拼接后仍然简单。候选被接纳后,它自己的后续分叉又被展开,新的分支代表项进入同一个全局候选池。只要最短支路遵守同一个排序,堆顶就是下一条应该输出的路径。
并列处理需要额外认真:总成本相同的情况下,边数和 ID 序列也参与比较;固定根前缀不会颠倒支路之间的顺序。因此上述分支比较不仅得到正确成本前缀,也得到本文定义的唯一完整顺序。原论文允许并列时任意选择,本文选择了更严格的工程契约,不把它归称为论文原本规定的次序。
每次接纳路径至多包含节点数减一条边,因此每轮至多产生这么多支路最短路请求。经典复杂度分析常把路径比较视为常数,并使用高效邻接表与前缀索引。本文是审计优先的参考实现:图构造采用逐节点扫描边,封锁集合逐次扫描已接纳路径,Python 元组的拼接、切片、哈希和比较都与路径长度有关,不能直接把某个教科书复杂度标签当成这份代码的精确运行成本。最坏情况下候选条目数随已输出数量与节点数的乘积增长,每条候选又保存整条路径,内存也需要计入。
简单路径总数本来就可能非常大。requestedK 较小可以避免枚举全集,但不保证每次探针便宜;预算、超时、输入规模与结果数量都应该有业务约束。若加入候选剪枝,必须另行证明仍保持前 K 的正确性;若选择近似算法,就应明确更换接口承诺。最稳妥的上线顺序是先固定图和排序契约,再用小图 oracle 对拍,最后用可重放快照定位真实业务图上的成本与性能问题。
参考资料与复核范围
Yen,Finding the K Shortest Loopless Paths in a Network,1971:算法出处;论文原文副本用于核对根前缀、支路与候选列表保留步骤。
NetworkX 官方接口文档:简单路径定义、非负加权限制与多重图接口边界。
Python heapq与Python sqlite3:优先队列、参数化 SQL、事务与连接关闭行为。
SQLite Isolation与SQLite Foreign Key Support:一致性与显式启用外键。
以上链接于 2026 年 10 月复核。代码和排序契约是本文给出的具体实现;有限测试只能覆盖列出的输入域,不应解释为对任意规模图的性能保证。

