Python sqlite3 桥边故障分析:用迭代 low-link 正确处理无向多重图
一份网络线路表能够回答哪些设备相连,却未必直接告诉我们:哪一条线路单独断开,就会把原本可达的设备分成两组?本文用 Python 标准库 sqlite3 保存无向多重图,再用迭代 low-link DFS 找到桥边。重点不是把算法名字写进 SQL,而是保住线路身份、正确处理回溯时机,并给结果配上一份可以从定义重新核验的证据。
运行要求为 Python 3.12 或更新版本,使用支持外键的 SQLite。本文实测环境为 Python 3.12.14、SQLite 3.53.1。九段 Python 程序均为独立完整脚本,各自创建内存数据库,只依赖标准库,不要求运行上一段或安装图算法库。保存为文件后,以 python -X dev -W error 文件名.py 运行;不要加会移除断言的 -O。每段后面给出实测的完整标准输出。

连接由 contextlib.closing 明确关闭。Python 官方文档说明,连接自己的 with 上下文负责事务处理,并不负责关闭连接。为了让事务边界明确,本文连接统一设置 autocommit=True;需要多语句原子操作时显式发送 BEGIN、COMMIT 或 ROLLBACK。示例中的外键、排序和事务行为分别可在文末官方资料核对。
一、先保存边的身份,不要把平行边去重
桥边是这样一条边:只删掉它,整个图的连通分量数就会增加。定义中的只删掉它很重要,两台设备之间若有两条独立线路,拔掉一条后另一条仍在;如果先用集合合并相同端点,输入就已经变成另一张图。本文固定讨论无向多重图,允许自环,允许不连通,也允许没有任何边的顶点。边的可靠性、方向、容量和多个故障同时发生,不属于本次模型。
节点表是完整的顶点清单,边表中的 id 则是线路身份。CHECK 只要求端点按较小编号在前存储,不会自动交换端点,没有对端点组合建立唯一约束,因此同一对端点能出现多行。主键不会要求编号连续,后面的测试也会使用零和负数作为边编号。外键保证端点存在;SQLite 官方文档明确提醒,必须按连接开启并检查外键,而且不能在事务中途才期待开关生效。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(1, 10)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [
(10, 1, 2), (11, 2, 3), (12, 1, 3), (20, 3, 4),
(30, 4, 5), (31, 4, 5), (40, 5, 6), (50, 4, 4), (60, 7, 8)
])
print("vertices:", len(load(db)[0]))
print("parallel:", list(db.execute(
"SELECT id FROM edge WHERE u = ? AND v = ? ORDER BY id", (4, 5))))
print("loops:", list(db.execute("SELECT id FROM edge WHERE u = v ORDER BY id")))
print("isolated:", list(db.execute("""
SELECT id FROM vertex AS n
WHERE NOT EXISTS(SELECT 1 FROM edge WHERE u = n.id OR v = n.id)
ORDER BY id
""")))
try:
db.execute("INSERT INTO edge VALUES(?, ?, ?)", (70, 8, 99))
except sqlite3.IntegrityError:
print("bad endpoint: rejected")输出:
vertices: 9 parallel: [(30,), (31,)] loops: [(50,)] isolated: [(9,)] bad endpoint: rejected
这张图有九个顶点:一到三组成三角形,三到四只有一条连接,四到五有两条平行边,五到六是叶子连接,四还有一个自环;七到八另成一组,九是孤立点。后续结果始终返回边编号,调用方再按编号关联设备或工单,不能仅用端点二元组代替。输入参数通过占位符传递;查询显式排序,避免把存储碰巧返回的顺序当成输出契约。
二、先写一个慢而直白的删除基准
优化前先把定义写成能运行的判定器。component_count 为每个顶点预留邻接表,逐个跳过已经访问的起点,因此孤立顶点也贡献一个分量,空图则得到零。skip 接收一条边的编号,只有这一行被排除;自环的两个邻接项可以保留,它们不会让搜索发现新顶点。
我们先求原始分量数,再逐条模拟删除。新分量数大于原值才是桥,不能简单检查删除后是否仍然只有一个分量:原始图本来就有三个分量,那种写法会把许多正常边也误判。这里不执行 DELETE,数据库中的输入保持完整,证据来自不同的内存邻接表。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def component_count(vertices, edges, skip=None):
adj = {v: [] for v in vertices}
for eid, u, v in edges:
if eid != skip:
adj[u].append(v)
adj[v].append(u)
seen = set()
count = 0
for start in vertices:
if start in seen:
continue
count += 1
seen.add(start)
todo = [start]
while todo:
for v in adj[todo.pop()]:
if v not in seen:
seen.add(v)
todo.append(v)
return count
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(1, 10)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [
(10, 1, 2), (11, 2, 3), (12, 1, 3), (20, 3, 4),
(30, 4, 5), (31, 4, 5), (40, 5, 6), (50, 4, 4), (60, 7, 8)
])
vertices, edges = load(db)
baseline = component_count(vertices, edges)
evidence = [(eid, component_count(vertices, edges, eid))
for eid, _, _ in edges]
expected = [eid for eid, count in evidence if count > baseline]
print("baseline:", baseline)
print("after deletion:", evidence)
print("bridges:", expected)输出:
baseline: 3 after deletion: [(10, 3), (11, 3), (12, 3), (20, 4), (30, 3), (31, 3), (40, 4), (50, 3), (60, 4)] bridges: [20, 40, 60]
这个判定器故意不用发现时间、父边或 low 值,它与后面的快速算法共享图数据格式,却不共享判断桥的逻辑。逐边删除需要反复遍历,时间复杂度是 O(E × (V + E));适合小图测试和故障证据核对,不适合在大型网络里充当主计算路径。独立基准的价值在于出现分歧时可以回到定义,而不是让两个几乎相同的实现互相证明。
三、用显式栈完成 low-link 深度优先搜索
tin 记录顶点第一次被发现的顺序,low 记录该顶点的 DFS 子树通过树边向下、再至多通过一条非树边回到祖先,能够触及的最早发现时间,也包含顶点自身。对树边父亲 p 到孩子 u,只有 low[u] 严格大于 tin[p] 才是桥;若相等,说明子树还有一条回到父亲的替代连接。
迭代版的难点是模拟递归返回。栈帧保存顶点和尚未消费完的邻接迭代器,发现孩子时只压入孩子,不提前计算父边结论。等孩子的迭代器耗尽,才弹栈、判断父边、把最终 low 值合并到父亲。非树边只使用对端的 tin 更新,不能随意拿对端未完成的 low 传播。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(1, 10)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [
(10, 1, 2), (11, 2, 3), (12, 1, 3), (20, 3, 4),
(30, 4, 5), (31, 4, 5), (40, 5, 6), (50, 4, 4), (60, 7, 8)
])
vertices, edges = load(db)
result = bridges(vertices, edges)
by_id = {eid: (u, v) for eid, u, v in edges}
print("bridges:", result)
print("endpoints:", [(eid, *by_id[eid]) for eid in result])输出:
bridges: [20, 40, 60] endpoints: [(20, 3, 4), (40, 5, 6), (60, 7, 8)]
外层循环从所有未发现顶点分别启动 DFS,所以不是只分析第一个连通分量。每条无向边加入两次邻接,包括自环;父边通过编号跳过,其他已发现邻居更新 low。无向 DFS 中若遇到已发现的后代,它的 tin 较大,不会降低当前值。每个邻接项只消费一次,DFS 核心时间和存储都是 O(V + E);返回时为稳定展示排序,还增加 O(B log B),B 是桥的数量。SQL 读取和报告生成的开销应另算。
为什么这个不等式成立?删去父树边后,DFS 树把孩子的整棵子树与外部分开。无向 DFS 中,若还有别的边跨过这道边界,它只能把子树中的某个顶点连向父亲或更早祖先,因而让 low[u] 不大于 tin[p];反过来,这样的返程边也确实提供一条绕过父树边的路。若不存在返程边,子树就失去与外部的连接。这同时解释了为何等号不是桥,以及平行的另一条边必须参与更新。
四、平行边反例:跳过父边,不是跳过父顶点
许多入门实现写成遇到父顶点就跳过。在简单图里,这恰好跳过来时那条边;在多重图里却会把另一条合法返程连接一起忽略。假设编号零和七都连接顶点十、二十,DFS 沿零号边进入二十后,只能忽略零号边的反向邻接,七号边必须把二十的 low 拉回十的 tin。
下面仍然完整定义算法,再从同一个数据库依次分析三种状态。两条平行边都在时,它们都不是桥;删除其中一条后,幸存的线路才变成桥;再添加自环,不会为两个不同顶点建立新通道,因此桥的结论不变。这里的 DELETE 只修改示例自己创建的内存库。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", [(10,), (20,)])
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [(0, 10, 20), (7, 10, 20)])
print("two parallel:", bridges(*load(db)))
db.execute("DELETE FROM edge WHERE id = ?", (0,))
print("one remaining:", bridges(*load(db)))
db.execute("INSERT INTO edge VALUES(?, ?, ?)", (-3, 20, 20))
print("with self-loop:", bridges(*load(db)))输出:
two parallel: [] one remaining: [7] with self-loop: [7]
None 是没有父边的标记,零和负数都可以是合法边编号,不能写成 if parent_edge[u] 来判断是否存在父边。自环遇到的始终是自身,更新值仍是自己的发现时间,也不会成为 DFS 树边。Princeton 的教学 Bridge.java 在源码说明中专门提示原版本假定没有平行边;本文保留的是 low-link 思路,数据身份与栈推进则围绕多重图重新实现。
五、空图、孤立点与多个 DFS 根都要有答案
边界条件最好单独列成可读的小表,而不是只藏在随机测试里。空图没有桥;若有三个孤立点,分量数是三但桥仍为空;只有自环的顶点也不会因为移除自环变得更不连通。一个图若包含两段互不相连的单边链,则两条边各自都是桥。
根节点只表示没有父边,不能对它执行父边判定。桥与割点是不同问题,割点算法里根节点孩子数量的特殊规则不能直接搬过来。此处从邻接字典遍历根,数据库读出顺序仅决定 DFS 树的形状,不应改变最终边编号集合。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
def component_count(vertices, edges, skip=None):
adj = {v: [] for v in vertices}
for eid, u, v in edges:
if eid != skip:
adj[u].append(v)
adj[v].append(u)
seen = set()
count = 0
for start in vertices:
if start in seen:
continue
count += 1
seen.add(start)
todo = [start]
while todo:
for v in adj[todo.pop()]:
if v not in seen:
seen.add(v)
todo.append(v)
return count
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
cases = [
("empty", [], []),
("isolated", [1, 2, 3], []),
("loop", [1], [(5, 1, 1)]),
("two components", [1, 2, 3, 4, 5], [(8, 1, 2), (9, 3, 4)]),
]
for name, vertices, edges in cases:
db.execute("DELETE FROM edge")
db.execute("DELETE FROM vertex")
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", edges)
vertices, edges = load(db)
print(name, "components=", component_count(vertices, edges),
"bridges=", bridges(vertices, edges))输出:
empty components= 0 bridges= [] isolated components= 3 bridges= [] loop components= 1 bridges= [] two components components= 3 bridges= [8, 9]
每轮先删边再删点,遵守外键约束;这些操作的目标只是隔离测试案例,并不是生产库的迁移方案。所有顶点都来自节点表,若只从边表收集端点,空图与孤立点的语义会悄悄消失。桥集合可能仍然碰巧正确,但分量数、影响范围与后续报告会错,不能据此认为输入建模无关紧要。
六、独立证书既查误报,也查漏报
只验证返回的每一条边删除后会断开,还不够:返回空列表的错误算法也能通过这种检查。完整核对必须对全部输入边执行删除基准,比较桥集合完全相等;另外检查返回编号唯一且确实存在,避免重复结果被集合化掩盖。下面同时保存原始分量数、每条边删除后的分量数,并让缺一条、错加自环两种伪结果都遭到拒绝。
这里称为独立删除证书,指的是可复查的判定记录和独立验证过程,并不声称它是线性大小、线性时间可验证的紧凑证明。打印出的计数用于解释,校验时必须从原始图重新计算,不能把求解器提供的计数当成可信输入。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
def component_count(vertices, edges, skip=None):
adj = {v: [] for v in vertices}
for eid, u, v in edges:
if eid != skip:
adj[u].append(v)
adj[v].append(u)
seen = set()
count = 0
for start in vertices:
if start in seen:
continue
count += 1
seen.add(start)
todo = [start]
while todo:
for v in adj[todo.pop()]:
if v not in seen:
seen.add(v)
todo.append(v)
return count
def verify(vertices, edges, candidate):
ids = {eid for eid, _, _ in edges}
if len(candidate) != len(set(candidate)) or not set(candidate) <= ids:
raise ValueError("invalid candidate IDs")
baseline = component_count(vertices, edges)
certificate = [(eid, component_count(vertices, edges, eid))
for eid, _, _ in edges]
expected = {eid for eid, count in certificate if count > baseline}
if set(candidate) != expected:
raise ValueError("bridge certificate mismatch")
return baseline, certificate
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(1, 10)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [
(10, 1, 2), (11, 2, 3), (12, 1, 3), (20, 3, 4),
(30, 4, 5), (31, 4, 5), (40, 5, 6), (50, 4, 4), (60, 7, 8)
])
vertices, edges = load(db)
answer = bridges(vertices, edges)
baseline, certificate = verify(vertices, edges, answer)
print("verified:", answer, "baseline:", baseline)
print("bridge evidence:", [(eid, count) for eid, count in certificate if eid in answer])
for name, bad in [("missing", answer[:-1]), ("false positive", answer + [50])]:
try:
verify(vertices, edges, bad)
except ValueError:
print(name + ": rejected")输出:
verified: [20, 40, 60] baseline: 3 bridge evidence: [(20, 4), (40, 4), (60, 4)] missing: rejected false positive: rejected
对无向图删除一条桥恰好增加一个分量;示例的三个桥都把计数从三变成四。独立验证不能替代输入快照:若求解时和验证时读取不同版本,分歧可能来自数据变化。生产环境要把节点、边以及证书绑定到同一快照或图版本,再讨论算法结果是否一致。
七、把桥转换成可以查询的故障影响报告
知道线路是桥之后,常见问题是它断开会让多少对节点失去互通。对一条桥,在原来的那个连通分量中,删除后分成大小为 a 与 b 的两侧,受影响的无序节点对数量就是 a × b。不能把全图总顶点数减去 a 当成 b,因为其他分量里的节点在故障前就不可达。下面以端点 u 为起点,先找原分量,再找删除后的同侧,差集才是另一侧。
报告计算和写入放在同一个 BEGIN IMMEDIATE 事务中,明确取得写事务后才读取输入。示例选择 autocommit=True,因此用 SQL 的 COMMIT 与 ROLLBACK 管理这个显式事务,不使用在该模式下无效的连接 commit 方法。SQLite 同一数据库只允许一个同时进行的写事务;锁竞争仍可能失败,实际应用需定义超时和重试策略。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
def reachable(start, edges, skip=None):
adj = {}
for eid, u, v in edges:
if eid != skip:
adj.setdefault(u, []).append(v)
adj.setdefault(v, []).append(u)
seen, todo = {start}, [start]
while todo:
for v in adj.get(todo.pop(), ()):
if v not in seen:
seen.add(v)
todo.append(v)
return seen
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(1, 10)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", [
(10, 1, 2), (11, 2, 3), (12, 1, 3), (20, 3, 4),
(30, 4, 5), (31, 4, 5), (40, 5, 6), (50, 4, 4), (60, 7, 8)
])
db.execute("""CREATE TABLE bridge_report(
edge_id INTEGER PRIMARY KEY REFERENCES edge(id),
side_a INTEGER NOT NULL,
side_b INTEGER NOT NULL,
lost_pairs INTEGER NOT NULL
)""")
db.execute("BEGIN IMMEDIATE")
try:
vertices, edges = load(db)
answer = set(bridges(vertices, edges))
rows = []
for eid, u, v in edges:
if eid in answer:
original = reachable(u, edges)
left = reachable(u, edges, eid)
right = original - left
assert u in left and v in right
rows.append((eid, len(left), len(right), len(left) * len(right)))
db.executemany("INSERT INTO bridge_report VALUES(?, ?, ?, ?)", rows)
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
print(list(db.execute("""
SELECT r.edge_id, e.u, e.v, r.side_a, r.side_b, r.lost_pairs
FROM bridge_report AS r JOIN edge AS e ON e.id = r.edge_id
ORDER BY r.lost_pairs DESC, r.edge_id
""")))输出:
[(20, 3, 4, 3, 3, 9), (40, 5, 6, 5, 1, 5), (60, 7, 8, 1, 1, 1)]
三到四这条桥两侧各有三个节点,所以影响九对;五到六影响五对;七到八只影响一对,孤立节点九完全不参与这三个乘积。报告不是实时维护视图,提交后任何相关边变化都可能让它过时;外键只约束编号存在,不能保证桥属性仍成立。生产方案应采用不可变图版本,或在写图时让报告失效并重算。当前逐桥搜索的报告也不是线性算法,代价约为 O(B × (V + E)),与快速识别桥的成本要分开。
八、长链验证迭代实现确实不依赖递归深度
小图上的正确结果并不能证明实现摆脱了递归。我们把一万条边存入 SQLite,组成一万零一个顶点的长链,然后完整读出并执行显式栈算法。链没有回路,每一条边都是桥。代码既不调用递归函数,也不修改解释器递归上限;栈帧存在普通 Python 列表里,深度由可用内存承担。
这项测试只核对长链的结构性答案,不对一万条边逐一运行慢删除基准。后者会把一个展示栈行为的案例变成无谓的平方级运行。要验证低层算法的组合边界,则交给下一节覆盖大量小图的穷举。
import sqlite3
from contextlib import closing
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
size = 10000
db.execute("BEGIN")
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(size + 1)))
db.executemany("INSERT INTO edge VALUES(?, ?, ?)",
((v + 1, v, v + 1) for v in range(size)))
db.execute("COMMIT")
vertices, edges = load(db)
answer = bridges(vertices, edges)
assert answer == list(range(1, size + 1))
print("vertices:", len(vertices), "edges:", len(edges))
print("bridges:", len(answer), "first:", answer[0], "last:", answer[-1])输出:
vertices: 10001 edges: 10000 bridges: 10000 first: 1 last: 10000
迭代并不等于无限规模。当前实现把顶点、边与双向邻接同时载入内存,还维护多个字典。对远大于内存的图,需要外存算法、分区方案或专用图处理工具,不能仅仅因为数据来自 SQLite 就认为 DFS 会自动在磁盘上进行。这里的分工很明确:数据库负责约束、持久化与查询,Python 负责当前快照上的图遍历。
九、穷举五万多张多重图,用定义反查实现
最后枚举零到四个带编号顶点。对每一对满足 u 不大于 v 的端点,边的重数可以为零、一或二;包括自环的端点对数为 n × (n + 1) / 2。因此总数是 1 + 3 + 27 + 729 + 59049,即 59809 张。这是一个明确限定的小图全集,不是宣称穷尽任意大小或任意重数的图。每张图都实际写入并读回 SQLite,再把快速算法与删除定义对比。
边编号使用带间隔的负整数,避免算法只在从一开始的连续编号上正常。测试过程中还把顶点和边的遍历顺序同时反转,再跑一次快速算法,验证结果不依赖 DFS 起点和邻接插入顺序。所有断言开启运行,任何差异都会终止脚本,而不是被汇总成一条看起来成功的计数。
import sqlite3
from contextlib import closing
from itertools import product
def setup(db):
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
id INTEGER PRIMARY KEY,
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id),
CHECK(u <= v)
);
""")
def load(db):
vertices = [r[0] for r in db.execute(
"SELECT id FROM vertex ORDER BY id")]
edges = list(db.execute("SELECT id, u, v FROM edge ORDER BY id"))
return vertices, edges
def bridges(vertices, edges):
adj = {v: [] for v in vertices}
ids = set()
for eid, u, v in edges:
if eid in ids or u not in adj or v not in adj:
raise ValueError("invalid edge identity or endpoint")
ids.add(eid)
adj[u].append((v, eid))
adj[v].append((u, eid))
tin, low, parent, parent_edge = {}, {}, {}, {}
clock = 0
answer = []
for root in adj:
if root in tin:
continue
parent[root] = parent_edge[root] = None
tin[root] = low[root] = clock
clock += 1
stack = [(root, iter(adj[root]))]
while stack:
u, neighbors = stack[-1]
item = next(neighbors, None)
if item is None:
stack.pop()
p = parent[u]
if p is not None:
if low[u] > tin[p]:
answer.append(parent_edge[u])
low[p] = min(low[p], low[u])
continue
v, eid = item
if eid == parent_edge[u]:
continue
if v not in tin:
parent[v], parent_edge[v] = u, eid
tin[v] = low[v] = clock
clock += 1
stack.append((v, iter(adj[v])))
else:
low[u] = min(low[u], tin[v])
return sorted(answer)
def component_count(vertices, edges, skip=None):
adj = {v: [] for v in vertices}
for eid, u, v in edges:
if eid != skip:
adj[u].append(v)
adj[v].append(u)
seen = set()
count = 0
for start in vertices:
if start in seen:
continue
count += 1
seen.add(start)
todo = [start]
while todo:
for v in adj[todo.pop()]:
if v not in seen:
seen.add(v)
todo.append(v)
return count
with closing(sqlite3.connect(":memory:", autocommit=True)) as db:
setup(db)
tested = 0
db.execute("BEGIN")
for n in range(5):
db.execute("DELETE FROM edge")
db.execute("DELETE FROM vertex")
db.executemany("INSERT INTO vertex VALUES(?)", ((v,) for v in range(n)))
pairs = [(u, v) for u in range(n) for v in range(u, n)]
for multiplicities in product(range(3), repeat=len(pairs)):
rows = []
for (u, v), count in zip(pairs, multiplicities):
for _ in range(count):
rows.append((-1000 + 7 * len(rows), u, v))
db.execute("DELETE FROM edge")
db.executemany("INSERT INTO edge VALUES(?, ?, ?)", rows)
vertices, edges = load(db)
baseline = component_count(vertices, edges)
expected = sorted(eid for eid, _, _ in edges
if component_count(vertices, edges, eid) > baseline)
actual = bridges(vertices, edges)
assert actual == expected, (n, multiplicities, actual, expected)
assert bridges(vertices[::-1], edges[::-1]) == expected
tested += 1
db.execute("COMMIT")
assert tested == 59809
print("graphs:", tested)
print("low-link vs deletion: PASS")
print("reversed traversal: PASS")输出:
graphs: 59809 low-link vs deletion: PASS reversed traversal: PASS
这组测试集中覆盖了父边误跳过、重复线路、自环、孤立点、多个根和返回时机等常见错误。它仍不替代证明,也不覆盖并发写入、数据库损坏或无限大的输入;它把有限范围说清楚,使任何人都能复现同一批检查。部署前还应对真实数据规模、事务耗时与内存上限单独做基准。桥只意味着单条边失效会增加连通分量,并不代表所有非桥线路都可以任意同时关闭。
收尾:把可解释性放进输出契约
一个可用的桥边分析器应返回稳定的边编号,承认不连通图和空输入,区分重复线路与重复记录,并能解释每个桥把哪个原始分量拆成哪两侧。核心判定只有一个严格不等式,可靠性却来自围绕它建立的数据约束、显式栈状态和独立测试。尤其要记住:父顶点可以相同,父边只能是那一个编号;孩子尚未完成时,不要提前读取它的最终 low 值。
如果业务里的两条线路实际共用同一根管道,图上平行边并不自动等于独立冗余。那是故障域建模问题,需要把共因失效表达进输入,再选择相应算法。本文解决的是输入图定义下的单边故障分析,不把连通性结论扩展成现实系统的可靠性保证。
官方与一手资料
Python sqlite3 官方文档:参数绑定、autocommit、显式连接关闭与事务上下文语义。
SQLite Foreign Key Support:每个连接启用外键,以及事务中修改开关的限制。
SQLite SELECT 官方文档:没有 ORDER BY 时,返回行顺序没有保证。
SQLite Transaction 官方文档:显式事务、读快照和 BEGIN IMMEDIATE 的写事务行为。
Princeton Algorithms Bridge.java 教学源码:low-link 思路与原示例不支持平行边的明确警告。本文没有照搬其仅适用于简单图的父顶点判断。
NetworkX bridges 官方文档:桥的删除定义及多重边处理说明。本文不依赖 NetworkX,使用独立删除基准作校验。
以上链接于 2026 年 10 月 19 日核验。算法代码与测试样例为本文独立编写;插画为本篇独立生成。

