Python sqlite3 最短路径实战:Dijkstra、零权环与独立距离证书

10-19 4阅读

路线规划、状态迁移代价和服务调用成本,都可能归结为同一个问题:从指定起点出发,沿有向边前进,到每个节点最少需要付出多少代价?当图已经存进 SQLite 时,容易写出的版本是边查数据库边更新一个距离字典;真正需要交付的版本,还必须回答数据是否来自同一时刻、旧堆记录会不会重复工作、零代价环如何终止,以及结果有没有独立于算法本身的验收办法。

本文使用 Python 标准库 sqlite3 和 heapq,将非负整数加权有向多重图读成一个一致性快照,再执行 Dijkstra。除距离外,还返回带边编号的前驱关系,并构造不重跑 Dijkstra 的距离证书验证器。最后用同步 Bellman–Ford 的独立递推,穷举三节点小图并检查带平行边的随机图。这里求的是最小权重和,不是最少经过几个节点,也不要求图无环。

Python sqlite3 最短路径实战:Dijkstra、零权环与独立距离证书
AI 生成的概念配图:数据库中的连接关系被读取,候选路线经过筛选;不代表本文样例的精确图结构或算法执行轨迹。

运行环境为 Python 3.12 及以上、SQLite 3.37.0 及以上,无需第三方库。九段代码均可单独保存为脚本,在新的 Python 进程中运行;每段后的普通文本框是完整标准输出。建议使用 python -X dev -W error example_01.py,且不要加会关闭断言的优化选项。所有示例数据在内存或自动清理的临时目录中创建,不读取已有业务数据库。示例中的连接显式指定 autocommit=True,并用 SQL 语句控制事务,避免依赖默认事务模式;该参数与连接关闭语义见 Python sqlite3 官方文档。

一、先固定图的语义:方向、权重与平行边

每条边保存独立编号 id、起点 src、终点 dst 和权重 weight。方向只能从 src 走到 dst;如果业务允许双向通行,就应明确保存两条有向边。节点表必须独立存在,否则完全没有边的节点会在读取时消失。边编号也不能用端点对代替,因为相同起终点之间可能存在价格不同、来源不同的平行边,而最终路径需要说明选择了哪一条。

本文只接受非负整数权重。STRICT 表、NOT NULL 和非负 CHECK 分别约束存储类型、空值和数值范围;每个连接还要开启外键,防止边引用不存在的节点。注意 STRICT 允许可无损的类型转换,并不保证调用方传入的原始 Python 对象就是整数。例如整数形式的字符串仍可能被转换,布尔值也会被绑定成整数;若接口要求拒绝这些输入,应在写入前单独校验。有关严格表的转换规则和版本门槛,见 SQLite STRICT Tables;外键的连接级开关见 SQLite 外键说明。

第一段同时保留两条平行边和一个孤立节点,并证明负数、小数和空权重被拒绝。这里测试的是数据库中的最终表示,不把数据库约束误当成整个输入协议。后续算法仍会再次检查权重,因为它也可能被直接用于内存数据。

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE node(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src INTEGER NOT NULL REFERENCES node(id),
    dst INTEGER NOT NULL REFERENCES node(id),
    weight INTEGER NOT NULL CHECK(weight >= 0)
) STRICT;
"""

def database(nodes, edges):
    con = sqlite3.connect(":memory:", autocommit=True)
    con.execute("PRAGMA foreign_keys = ON")
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?)", [(v,) for v in nodes])
    con.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)
    return con

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(row[0] for row in con.execute("SELECT id FROM node ORDER BY id"))
        edges = tuple(con.execute("SELECT id, src, dst, weight FROM edge ORDER BY id"))
        con.execute("COMMIT")
        return nodes, edges
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

with closing(database([1, 2, 3], [(10, 1, 2, 0), (11, 1, 2, 7)])) as con:
    print("nodes:", con.execute("SELECT count(*) FROM node").fetchone()[0])
    print("parallel:", con.execute("SELECT count(*) FROM edge WHERE src=1 AND dst=2").fetchone()[0])
    for weight in (-1, 1.5, None):
        try:
            con.execute("INSERT INTO edge VALUES(20, 1, 2, ?)", (weight,))
        except sqlite3.IntegrityError:
            print(repr(weight), "rejected")
    print("zero:", con.execute("SELECT weight FROM edge WHERE id=10").fetchone()[0])

运行结果:

nodes: 3
parallel: 2
-1 rejected
1.5 rejected
None rejected
zero: 0

database 是教学用建库函数;snapshot 是后续示例使用的读取边界,要求连接当前没有活动事务,且由调用方独占。函数内的两次查询分别读取节点和边,但都落在同一次读事务中。每段脚本重新包含需要的函数,不需要从前一个示例导入文件。

二、读快照必须从首次实际读取开始理解

假设先读出节点列表,另一个连接紧接着修改边,再继续读取边列表。若这两次查询分属不同事务,得到的可能是从未作为整体存在过的图。解决方法不是给查询加排序,而是把相关读取放进同一个显式读事务,然后把结果物化为 Python 元组。排序负责稳定顺序,事务负责一致性,两者不能互相替代。

下面使用临时文件和两个独立连接,在 WAL 模式下安排一条可重复的时间线:读者开始事务并实际读到权重九;写者提交权重二;读者在旧事务里仍看到九;结束事务后才看到二。无需线程或 sleep,执行顺序本身就是控制条件。普通 BEGIN 是延迟事务,不能把发出 BEGIN 的瞬间直接当成快照已经固定;首次数据库访问才使读事务实际开始。规则见 SQLite 延迟事务说明,并发读取行为见 SQLite 隔离说明。

import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "graph.db"
    with closing(sqlite3.connect(path, autocommit=True)) as writer:
        assert writer.execute("PRAGMA journal_mode=WAL").fetchone()[0] == "wal"
        writer.execute("CREATE TABLE edge(id INTEGER PRIMARY KEY, weight INTEGER NOT NULL) STRICT")
        writer.execute("INSERT INTO edge VALUES(1, 9)")
        with closing(sqlite3.connect(path, autocommit=True)) as reader:
            reader.execute("BEGIN")
            old = reader.execute("SELECT weight FROM edge WHERE id=1").fetchone()[0]
            writer.execute("UPDATE edge SET weight=2 WHERE id=1")
            same = reader.execute("SELECT weight FROM edge WHERE id=1").fetchone()[0]
            reader.execute("COMMIT")
            fresh = reader.execute("SELECT weight FROM edge WHERE id=1").fetchone()[0]
            assert (old, same, fresh) == (9, 9, 2)
            print("before:", old)
            print("same snapshot:", same)
            print("after commit:", fresh)

运行结果:

before: 9
same snapshot: 9
after commit: 2

本例特意使用 WAL,使写者能在读者持有快照时提交。算法本身不要求开启 WAL;不同日志模式主要影响并发和锁等待。完整读入后立即提交读事务,再在内存中做堆运算,可以缩短持有快照的时间。不要在读图的同一个连接上穿插修改,因为同连接自己的更新会被后续查询看到。生产环境的超时、重试和批量写入原子性需要另行设计,本例不声称解决所有并发问题。

三、Dijkstra 的关键不是入堆,而是识别旧记录

dist 保存当前最好距离,None 表示尚不可达,起点距离为零。堆里存放距离和节点编号,每次拿出距离最小的候选,再尝试改进它的出边终点。只有候选距离严格更小时才更新。非负权重保证一个节点以当前最好距离弹出后,不会被后来经过更远节点的路线再次严格改善。这是 Dijkstra 适用条件的核心,参见 MIT 6.006 Dijkstra 课程讲义。

heapq 不提供直接定位某条记录并降低优先级的接口。这里采用惰性策略:每次发现更短距离就再入堆,旧记录留到将来弹出时处理。弹出的 du 若不等于 dist[u],说明它已经过期,必须跳过。不要扫描堆去删除旧项,也不要把第一次入堆误认为最终确定。优先队列更新与失效记录的基本处理方式可对照 heapq 官方说明。

样例中节点一先以距离九进入堆,随后被零到二再到一的路线改善为三。节点三也先得到十,随后改善为三。因此最终有两条旧记录被跳过。两条从零到二的平行边全部保留,但较贵的一条不会改进距离。注意示例读取完快照后已经关闭数据库,后续结果仅对应刚才读到的那份数据。

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE node(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src INTEGER NOT NULL REFERENCES node(id),
    dst INTEGER NOT NULL REFERENCES node(id),
    weight INTEGER NOT NULL CHECK(weight >= 0)
) STRICT;
"""

def database(nodes, edges):
    con = sqlite3.connect(":memory:", autocommit=True)
    con.execute("PRAGMA foreign_keys = ON")
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?)", [(v,) for v in nodes])
    con.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)
    return con

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(row[0] for row in con.execute("SELECT id FROM node ORDER BY id"))
        edges = tuple(con.execute("SELECT id, src, dst, weight FROM edge ORDER BY id"))
        con.execute("COMMIT")
        return nodes, edges
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

from heapq import heappop, heappush

def shortest(nodes, edges, source):
    if any(type(v) is not int for v in nodes) or len(set(nodes)) != len(nodes):
        raise ValueError("invalid nodes")
    adj = {v: [] for v in nodes}
    if type(source) is not int or source not in adj:
        raise ValueError("unknown source")
    edge_ids = set()
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in edge_ids or u not in adj or v not in adj or w < 0):
            raise ValueError("invalid edge")
        edge_ids.add(eid)
        adj[u].append((v, w, eid))
    for outgoing in adj.values():
        outgoing.sort()
    dist = {v: None for v in nodes}
    pred = {v: None for v in nodes}
    dist[source] = 0
    heap = [(0, source)]
    stale = 0
    while heap:
        du, u = heappop(heap)
        if du != dist[u]:
            stale += 1
            continue
        for v, w, eid in adj[u]:
            candidate = du + w
            if dist[v] is None or candidate < dist[v]:
                dist[v] = candidate
                pred[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, pred, stale

nodes = [0, 1, 2, 3, 4]
edges = [(10, 0, 1, 9), (11, 0, 2, 2), (12, 2, 1, 1),
         (13, 1, 3, 0), (14, 2, 3, 8), (15, 0, 2, 5)]
with closing(database(nodes, edges)) as con:
    nodes, edges = snapshot(con)
dist, pred, stale = shortest(nodes, edges, 0)
assert dist == {0: 0, 1: 3, 2: 2, 3: 3, 4: None}
assert stale == 2
print("dist:", sorted(dist.items()))
print("predecessor of 1:", pred[1])
print("stale:", stale)

运行结果:

dist: [(0, 0), (1, 3), (2, 2), (3, 3), (4, None)]
predecessor of 1: (2, 12)
stale: 2

距离表包含全部节点,孤立节点四保留为 None。前驱使用二元组保存前一节点和具体边编号,因此即使端点相同也能审计路线。邻接表按终点、权重、边编号排序;堆按距离、整数节点编号排序。没有隐藏依赖 SQL 返回顺序,也没有把不可比较的任意对象直接塞进同优先级元组。

四、零权环可以存在,但相等距离不要改前驱

非负不是严格为正。零权边代表允许免费转移的业务动作,零权自环和零权环也都可以存在。它们不会让最短距离无限下降,却会让某些错误实现不断重复入堆:若使用小于等于作为更新条件,走一圈回到同一距离后仍会更新,算法就可能无法停止。即使只改前驱不入堆,等距覆盖也可能把一棵前驱树改成环。

本实现只在严格改善时改距离和前驱。节点一先由起点获得零,再通过零权边发现节点二;回到节点一的零权边无法继续改善零,因此不做任何事。零权自环同理。两个完全同权的平行边,由排序后先遇到的较小边编号胜出,但这个规则只负责可重复性,不代表业务上存在额外偏好。

from heapq import heappop, heappush

def shortest(nodes, edges, source):
    if any(type(v) is not int for v in nodes) or len(set(nodes)) != len(nodes):
        raise ValueError("invalid nodes")
    adj = {v: [] for v in nodes}
    if type(source) is not int or source not in adj:
        raise ValueError("unknown source")
    edge_ids = set()
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in edge_ids or u not in adj or v not in adj or w < 0):
            raise ValueError("invalid edge")
        edge_ids.add(eid)
        adj[u].append((v, w, eid))
    for outgoing in adj.values():
        outgoing.sort()
    dist = {v: None for v in nodes}
    pred = {v: None for v in nodes}
    dist[source] = 0
    heap = [(0, source)]
    stale = 0
    while heap:
        du, u = heappop(heap)
        if du != dist[u]:
            stale += 1
            continue
        for v, w, eid in adj[u]:
            candidate = du + w
            if dist[v] is None or candidate < dist[v]:
                dist[v] = candidate
                pred[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, pred, stale

nodes = [0, 1, 2, 3]
edges = [(5, 0, 1, 0), (6, 0, 1, 0), (7, 1, 2, 0),
         (8, 2, 1, 0), (9, 2, 2, 0), (10, 0, 2, 4)]
dist, pred, stale = shortest(nodes, edges, 0)
assert pred[1] == (0, 5) and pred[2] == (1, 7)
assert pred[0] is None and pred[3] is None
print("dist:", sorted(dist.items()))
print("parents:", sorted(pred.items()))
print("stale:", stale)

运行结果:

dist: [(0, 0), (1, 0), (2, 0), (3, None)]
parents: [(0, None), (1, (0, 5)), (2, (1, 7)), (3, None)]
stale: 1

前驱链仍然向起点收敛,其理由不依赖距离必须严格下降。每次建立前驱时,前驱节点正在以有效最小距离展开;它后来不会被严格改善,而等距候选也不会改写关系。因此可以安全构造一条具体最短路径。若把算法改成允许负边或等距替换,就必须重新审查这份论证,不能只沿用原先的输出测试。

五、确定性平局规则与全局字典序不是一回事

多个最短路径可能具有相同权重。本文采用明确且容易复现的规则:同距离节点按整数编号弹出,同一节点的出边按终点、权重和边编号处理,等距路线保留先得到的前驱。只要节点、边编号、权重和起点相同,插入顺序变化不会改变结果。下面枚举四条边的全部二十四种顺序,确认前驱映射只有一种。

这个规则并没有承诺整条路径的节点序列字典序最小,也没有承诺使用边数最少,更没有承诺最后一条边编号最小。样例到节点三会保留经节点一、边编号四十的路径,而不会仅因为另一条终边编号二十较小就改选。若产品需要少换乘、少跳数或指定线路优先,应先把优化目标写成清晰契约,再设计对应的标签和比较方式;不能在等距分支临时拼凑几条判断。

from heapq import heappop, heappush

def shortest(nodes, edges, source):
    if any(type(v) is not int for v in nodes) or len(set(nodes)) != len(nodes):
        raise ValueError("invalid nodes")
    adj = {v: [] for v in nodes}
    if type(source) is not int or source not in adj:
        raise ValueError("unknown source")
    edge_ids = set()
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in edge_ids or u not in adj or v not in adj or w < 0):
            raise ValueError("invalid edge")
        edge_ids.add(eid)
        adj[u].append((v, w, eid))
    for outgoing in adj.values():
        outgoing.sort()
    dist = {v: None for v in nodes}
    pred = {v: None for v in nodes}
    dist[source] = 0
    heap = [(0, source)]
    stale = 0
    while heap:
        du, u = heappop(heap)
        if du != dist[u]:
            stale += 1
            continue
        for v, w, eid in adj[u]:
            candidate = du + w
            if dist[v] is None or candidate < dist[v]:
                dist[v] = candidate
                pred[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, pred, stale

from itertools import permutations

nodes = [0, 1, 2, 3]
edges = [(30, 0, 2, 1), (20, 2, 3, 1),
         (10, 0, 1, 1), (40, 1, 3, 1)]
answers = set()
for order in permutations(edges):
    dist, pred, _ = shortest(nodes, order, 0)
    assert dist[3] == 2
    answers.add(tuple(sorted(pred.items())))
assert len(answers) == 1
print("orders:", 24)
print("distinct predecessor maps:", len(answers))
print("predecessor of 3:", dict(next(iter(answers)))[3])

运行结果:

orders: 24
distinct predecessor maps: 1
predecessor of 3: (1, 40)

可重复性是针对同一编号体系的承诺。如果重新导入数据时重新分配边编号,或改变节点编号映射,相同业务关系未必产生相同前驱树。验收时应同时记录使用的图版本、起点和选择规则。距离本身不受这些平局规则影响,但路径解释可能变化。

六、路径恢复要区分不可达、起点与非法输入

距离和路径是两个不同输出。起点到自己有一条空边路径,顶点序列只包含起点;不可达节点则没有路径。下面分别返回顶点序列和边编号序列,避免空列表的含义被混淆。恢复过程中加入已访问集合,是为了在前驱数据被意外修改时及时报错,而不是在循环中耗尽资源。

这里的 route 仅用于本算法返回的、同一起点的前驱映射;它不是接收任意外部 JSON 的完整校验器。负边必须在主循环开始前被拒绝,即使这条负边位于起点暂时到不了的区域,也不应该悄悄绕过整个函数的输入契约。不存在的起点与真实存在但不可达的终点也是两种情况,前者是请求错误,后者是合法计算结果。

from heapq import heappop, heappush

def shortest(nodes, edges, source):
    if any(type(v) is not int for v in nodes) or len(set(nodes)) != len(nodes):
        raise ValueError("invalid nodes")
    adj = {v: [] for v in nodes}
    if type(source) is not int or source not in adj:
        raise ValueError("unknown source")
    edge_ids = set()
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in edge_ids or u not in adj or v not in adj or w < 0):
            raise ValueError("invalid edge")
        edge_ids.add(eid)
        adj[u].append((v, w, eid))
    for outgoing in adj.values():
        outgoing.sort()
    dist = {v: None for v in nodes}
    pred = {v: None for v in nodes}
    dist[source] = 0
    heap = [(0, source)]
    stale = 0
    while heap:
        du, u = heappop(heap)
        if du != dist[u]:
            stale += 1
            continue
        for v, w, eid in adj[u]:
            candidate = du + w
            if dist[v] is None or candidate < dist[v]:
                dist[v] = candidate
                pred[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, pred, stale

def route(pred, dist, source, target):
    if target not in dist:
        raise ValueError("unknown target")
    if dist[target] is None:
        return [], []
    vertices, edge_ids, seen = [], [], set()
    v = target
    while v != source:
        if v in seen or pred[v] is None:
            raise ValueError("broken predecessor chain")
        seen.add(v)
        vertices.append(v)
        v, eid = pred[v]
        edge_ids.append(eid)
    vertices.append(source)
    return vertices[::-1], edge_ids[::-1]

nodes = [0, 1, 2, 3, 4]
edges = [(10, 0, 1, 9), (11, 0, 2, 2), (12, 2, 1, 1), (13, 1, 3, 0)]
dist, pred, _ = shortest(nodes, edges, 0)
print("to 3:", route(pred, dist, 0, 3))
print("to 4:", route(pred, dist, 0, 4))
print("to self:", route(pred, dist, 0, 0))
try:
    shortest(nodes, [(99, 0, 1, -1)], 0)
except ValueError as error:
    print("negative:", str(error))
try:
    shortest(nodes, edges, 99)
except ValueError as error:
    print("missing source:", str(error))

运行结果:

to 3: ([0, 2, 1, 3], [11, 12, 13])
to 4: ([], [])
to self: ([0], [])
negative: invalid edge
missing source: unknown source

Python 整数加法可以保留很大的路径权重和,因此不需要把距离转换成浮点数,也不用选择一个可能过小的魔法上界。SQLite INTEGER 存储单条权重时仍有有符号六十四位边界;把多条边相加后,Python 中的总距离可以超过该边界。若以后要将总距离写回 INTEGER 列,应先检查范围,不能把本篇的内存计算能力当成数据库存储能力。

七、距离证书:全边不等式加真实前驱路径

独立验证器不需要再运行优先队列。它读取同一份节点、边、起点以及候选 dist 和 pred,先检查键集合、数值域、起点距离和边编号,再检查两类约束。第一类是全边不等式:只要边的起点距离有限,终点也必须有限,且终点距离不能大于起点距离加边权。它防止遗漏可达节点,也防止结果把某条已知路线算得过贵。

第二类是前驱证据:每个有限且非起点的节点必须给出一条真实指向自己的边,并且距离恰好等于前驱距离加这条边的权重。验证器用前驱边构建孩子列表,再从起点遍历,要求最终恰好覆盖所有有限节点。这一步保证每个有限距离都对应从起点实际走得到的路径,而不是孤立在另一个分量里的漂亮数字。

正确性的双向夹逼可以直接检查:沿任意真实起点路径反复使用全边不等式,得到候选距离不大于这条路径的代价,因此不大于最短距离;沿已验证的有根前驱链累加等式,又得到一条代价恰好等于候选距离的实际路径,因此最短距离不大于候选距离。两者合起来才证明相等。下面的验证器是本文针对整数多重图独立编写的检查逻辑,没有调用 shortest,也不依赖它的堆状态。

def certify(nodes, edges, source, dist, pred):
    vertices = set(nodes)
    if (type(source) is not int or len(vertices) != len(nodes) or source not in vertices
            or any(type(v) is not int for v in nodes)
            or set(dist) != vertices or set(pred) != vertices):
        return False
    if dist[source] != 0 or pred[source] is not None:
        return False
    if any(d is not None and (type(d) is not int or d < 0)
           for d in dist.values()):
        return False
    by_id = {}
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in by_id or u not in vertices or v not in vertices or w < 0):
            return False
        by_id[eid] = (u, v, w)
        if dist[u] is not None:
            if dist[v] is None or dist[v] > dist[u] + w:
                return False
    children = {v: [] for v in nodes}
    finite = {v for v in nodes if dist[v] is not None}
    for v in nodes:
        if v not in finite or v == source:
            if pred[v] is not None:
                return False
            continue
        p = pred[v]
        if (not isinstance(p, tuple) or len(p) != 2
                or any(type(x) is not int for x in p)):
            return False
        u, eid = p
        edge = by_id.get(eid)
        if edge is None or edge[:2] != (u, v) or u not in finite:
            return False
        if dist[v] != dist[u] + edge[2]:
            return False
        children[u].append(v)
    seen = {source}
    todo = [source]
    while todo:
        for v in children[todo.pop()]:
            if v in seen:
                return False
            seen.add(v)
            todo.append(v)
    return seen == finite

nodes = [0, 1, 2, 3, 4]
edges = [(10, 0, 1, 9), (11, 0, 2, 2), (12, 2, 1, 1),
         (13, 1, 3, 0), (14, 2, 3, 8), (15, 0, 2, 5)]
dist = {0: 0, 1: 3, 2: 2, 3: 3, 4: None}
pred = {0: None, 1: (2, 12), 2: (0, 11), 3: (1, 13), 4: None}
assert certify(nodes, edges, 0, dist, pred)
print("valid:", certify(nodes, edges, 0, dist, pred))
print("too large:", certify(nodes, edges, 0, dist | {1: 9}, pred))
print("too small:", certify(nodes, edges, 0, dist | {3: 2}, pred))
print("false unreachable:", certify(nodes, edges, 0, dist | {3: None}, pred | {3: None}))
print("wrong parallel edge:", certify(nodes, edges, 0, dist, pred | {2: (0, 15)}))

运行结果:

valid: True
too large: False
too small: False
false unreachable: False
wrong parallel edge: False

把距离改大、改小、把真实可达节点标成不可达、或者给平行边选错编号,都必须验收失败。认证复杂度按节点和边线性增长,额外空间也是线性的;这里使用显式栈而非递归,避免长路径触及 Python 递归深度。验证器假设参数已经是示例这种容器形状,如果从外部格式导入,还需要在它之前完成结构解析与输入大小限制。

八、为什么只验等式会被零权环骗过

构造一个更危险的反例:起点零完全孤立,节点一与二之间有两个零权方向相反的边。若伪造它们距离都为零,并让它们互为前驱,那么每条边的不等式都成立,每条前驱等式也成立。仅检查数值关系的程序会误把另一个分量当成免费可达区域。

问题在于这些等式没有说明从哪里出发。有根性检查要求从起点顺着前驱树的孩子关系走遍所有有限节点,因而能识别这份伪证书。不能用距离严格下降来代替,因为合法零权前驱边两端的距离本来就相等。也不能简单禁止所有零权环,因为原图有环与所选前驱关系有环是不同概念;前者可以合法存在,后者不能成为一条起点路径的证明。

def certify(nodes, edges, source, dist, pred):
    vertices = set(nodes)
    if (type(source) is not int or len(vertices) != len(nodes) or source not in vertices
            or any(type(v) is not int for v in nodes)
            or set(dist) != vertices or set(pred) != vertices):
        return False
    if dist[source] != 0 or pred[source] is not None:
        return False
    if any(d is not None and (type(d) is not int or d < 0)
           for d in dist.values()):
        return False
    by_id = {}
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in by_id or u not in vertices or v not in vertices or w < 0):
            return False
        by_id[eid] = (u, v, w)
        if dist[u] is not None:
            if dist[v] is None or dist[v] > dist[u] + w:
                return False
    children = {v: [] for v in nodes}
    finite = {v for v in nodes if dist[v] is not None}
    for v in nodes:
        if v not in finite or v == source:
            if pred[v] is not None:
                return False
            continue
        p = pred[v]
        if (not isinstance(p, tuple) or len(p) != 2
                or any(type(x) is not int for x in p)):
            return False
        u, eid = p
        edge = by_id.get(eid)
        if edge is None or edge[:2] != (u, v) or u not in finite:
            return False
        if dist[v] != dist[u] + edge[2]:
            return False
        children[u].append(v)
    seen = {source}
    todo = [source]
    while todo:
        for v in children[todo.pop()]:
            if v in seen:
                return False
            seen.add(v)
            todo.append(v)
    return seen == finite

nodes = [0, 1, 2]
edges = [(10, 1, 2, 0), (11, 2, 1, 0)]
forged_dist = {0: 0, 1: 0, 2: 0}
forged_pred = {0: None, 1: (2, 11), 2: (1, 10)}
inequalities = all(forged_dist[v] <= forged_dist[u] + w for _, u, v, w in edges)
by_id = {eid: (u, v, w) for eid, u, v, w in edges}
tight = all(forged_dist[v] == forged_dist[u] + by_id[eid][2]
            for v, p in forged_pred.items() if p is not None for u, eid in [p])
print("edge inequalities:", inequalities)
print("predecessor equality:", tight)
print("rooted certificate:", certify(nodes, edges, 0, forged_dist, forged_pred))
real_dist = {0: 0, 1: None, 2: None}
real_pred = {0: None, 1: None, 2: None}
print("real certificate:", certify(nodes, edges, 0, real_dist, real_pred))

运行结果:

edge inequalities: True
predecessor equality: True
rooted certificate: False
real certificate: True

这类反例值得长期保留为回归测试。普通正权样例很难暴露问题,因为正权前驱等式通常会迫使距离下降;一旦业务后来引入免费转移,原来的简化验证就可能失效。证书的作用正是把隐含假设变成显式检查,而不是仅为已经相信的结果打印一个通过标记。

九、用不同算法与穷举小图建立交叉证据

测试不能只把同一个函数调用两遍再比较。最后的 oracle 使用同步 Bellman–Ford 递推:第 k 轮只读取上一轮距离,表示最多使用 k 条边能够获得的最好结果。非负图的最短路线可以去除环而不变贵,因此若可达,总能找到至多节点数减一条边的简单路径。这给出了有限轮数,也避开了堆、过期项和 Dijkstra 弹出顺序。

先对三节点的六个非自环有向位置分别选择缺边、权重零或权重二,共得到七百二十九张图;每张图测试三个起点。然后用固定随机种子生成一百二十张允许自环、重复端点和零权的多重图。每一次都真正写入 SQLite、在同一快照读取,再分别执行待测算法、独立递推和证书校验。最后额外检查两条最大六十四位整数权重组成的路径,确认加法没有偷偷变成浮点。

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE node(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src INTEGER NOT NULL REFERENCES node(id),
    dst INTEGER NOT NULL REFERENCES node(id),
    weight INTEGER NOT NULL CHECK(weight >= 0)
) STRICT;
"""

def database(nodes, edges):
    con = sqlite3.connect(":memory:", autocommit=True)
    con.execute("PRAGMA foreign_keys = ON")
    con.executescript(SCHEMA)
    con.executemany("INSERT INTO node VALUES(?)", [(v,) for v in nodes])
    con.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)
    return con

def snapshot(con):
    con.execute("BEGIN")
    try:
        nodes = tuple(row[0] for row in con.execute("SELECT id FROM node ORDER BY id"))
        edges = tuple(con.execute("SELECT id, src, dst, weight FROM edge ORDER BY id"))
        con.execute("COMMIT")
        return nodes, edges
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

from heapq import heappop, heappush

def shortest(nodes, edges, source):
    if any(type(v) is not int for v in nodes) or len(set(nodes)) != len(nodes):
        raise ValueError("invalid nodes")
    adj = {v: [] for v in nodes}
    if type(source) is not int or source not in adj:
        raise ValueError("unknown source")
    edge_ids = set()
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in edge_ids or u not in adj or v not in adj or w < 0):
            raise ValueError("invalid edge")
        edge_ids.add(eid)
        adj[u].append((v, w, eid))
    for outgoing in adj.values():
        outgoing.sort()
    dist = {v: None for v in nodes}
    pred = {v: None for v in nodes}
    dist[source] = 0
    heap = [(0, source)]
    stale = 0
    while heap:
        du, u = heappop(heap)
        if du != dist[u]:
            stale += 1
            continue
        for v, w, eid in adj[u]:
            candidate = du + w
            if dist[v] is None or candidate < dist[v]:
                dist[v] = candidate
                pred[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, pred, stale

def certify(nodes, edges, source, dist, pred):
    vertices = set(nodes)
    if (type(source) is not int or len(vertices) != len(nodes) or source not in vertices
            or any(type(v) is not int for v in nodes)
            or set(dist) != vertices or set(pred) != vertices):
        return False
    if dist[source] != 0 or pred[source] is not None:
        return False
    if any(d is not None and (type(d) is not int or d < 0)
           for d in dist.values()):
        return False
    by_id = {}
    for eid, u, v, w in edges:
        if (any(type(x) is not int for x in (eid, u, v, w))
                or eid in by_id or u not in vertices or v not in vertices or w < 0):
            return False
        by_id[eid] = (u, v, w)
        if dist[u] is not None:
            if dist[v] is None or dist[v] > dist[u] + w:
                return False
    children = {v: [] for v in nodes}
    finite = {v for v in nodes if dist[v] is not None}
    for v in nodes:
        if v not in finite or v == source:
            if pred[v] is not None:
                return False
            continue
        p = pred[v]
        if (not isinstance(p, tuple) or len(p) != 2
                or any(type(x) is not int for x in p)):
            return False
        u, eid = p
        edge = by_id.get(eid)
        if edge is None or edge[:2] != (u, v) or u not in finite:
            return False
        if dist[v] != dist[u] + edge[2]:
            return False
        children[u].append(v)
    seen = {source}
    todo = [source]
    while todo:
        for v in children[todo.pop()]:
            if v in seen:
                return False
            seen.add(v)
            todo.append(v)
    return seen == finite

from itertools import product
from random import Random

def oracle(nodes, edges, source):
    # Synchronous Bellman-Ford: paths using at most k edges.
    previous = {v: None for v in nodes}
    previous[source] = 0
    for _ in range(len(nodes) - 1):
        current = previous.copy()
        for _, u, v, w in edges:
            if previous[u] is not None:
                candidate = previous[u] + w
                if current[v] is None or candidate < current[v]:
                    current[v] = candidate
        previous = current
    return previous

def check(nodes, edges, source):
    with closing(database(nodes, edges)) as con:
        loaded_nodes, loaded_edges = snapshot(con)
    dist, pred, _ = shortest(loaded_nodes, loaded_edges, source)
    assert dist == oracle(loaded_nodes, loaded_edges, source)
    assert certify(loaded_nodes, loaded_edges, source, dist, pred)

pairs = [(u, v) for u in range(3) for v in range(3) if u != v]
count = 0
for choices in product((None, 0, 2), repeat=6):
    edges = [(i, u, v, w) for i, ((u, v), w) in enumerate(zip(pairs, choices))
             if w is not None]
    for source in range(3):
        check([0, 1, 2], edges, source)
        count += 1
rng = Random(20261019)
for _ in range(120):
    n = rng.randint(1, 7)
    edges = [(i, rng.randrange(n), rng.randrange(n), rng.randrange(6))
             for i in range(rng.randrange(25))]
    check(list(range(n)), edges, rng.randrange(n))
    count += 1
big = 2**63 - 1
check([0, 1, 2], [(1, 0, 1, big), (2, 1, 2, big)], 0)
print("exhaustive cases:", 729 * 3)
print("seeded multigraph cases:", 120)
print("large integer case:", "passed")
print("all checks:", count + 1)

运行结果:

exhaustive cases: 2187
seeded multigraph cases: 120
large integer case: passed
all checks: 2308

这组检查覆盖两千三百零八次计算,能发现方向颠倒、漏节点、平行边被覆盖、零权被误判为空值等常见错误,但有限测试仍不是对任意规模输入的数学证明。它与前面的算法条件、证书论证形成互补。固定随机种子负责可重复,小图穷举负责系统覆盖,专门构造的伪证书负责攻击验证器的盲点。

落地边界:先保证正确,再考虑扩大规模

设节点数为 V、边数为 E。本文的惰性堆允许同一节点存在多条历史记录,因此不能直接套用只保存每个节点一个堆条目的空间分析。在整数运算视作常数时间的通常模型下,建表以外的内存算法总时间可界为 O(V + E log(E + 1)),包括邻接排序和堆操作;图、距离、前驱与堆占 O(V + E) 空间。大量平行边会让 E 远大于 V。特别大的整数还要计入加法和比较的位复杂度。

整图物化适合能够装入内存的静态快照。若图太大,应重新评估分区、持久化索引、外存算法或专用图处理方案,不能只是把 fetchall 换成游标就宣称内存问题已经消失,因为邻接表和堆仍然保留数据。若只关心一个终点,可以讨论有效最小距离弹出时提前结束,但那样返回的全图距离并不都已完成,不能直接交给本文的全图证书验证器。

最后,把结果与其输入绑定起来同样重要:图更新后,旧距离只对旧快照负责。生产流程可以记录业务版本号或对规范化输入计算摘要,并在使用结果时核对版本。摘要只标识数据,不证明算法正确;证书证明的是给定图和起点上的距离,也不会替你证明业务把费用、时间或权限建模正确。把存储约束、快照边界、算法契约、路径证据和独立对照分别做好,才能让最短路径结果真正可解释、可复核。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。