目录
正在加载目录…
正在阅读专栏 Algorithms:CLRS + MIT 6.006 第 13 篇 · 共 24 篇 · 54%

Breadth-First Search:图搜索与最短路径树

发布于 2026-09-18 18:41 · 最后编辑于 2026-09-18 18:41 · 版本 v1 · 字数 4,981 · 预计阅读 10 分钟 👁 14 次阅读

Algorithms:Breadth-First Search

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 13《Breadth-First Search》,从 graph terminology 和 graph-search applications 出发,介绍 adjacency lists、implicit graphs、incidence lists,以及按 level 扩展的 breadth-first search(BFS);最后证明 BFS 得到的 levels 是从 source 出发的 shortest-path distances。

TL;DR

  • Graph:G=(V,E),V 是 vertices set,E 是 vertex pairs;ordered pair 表示 directed edge,unordered pair 表示 undirected edge。
  • Representation:显式 graph 可以用 adjacency lists,空间为 Θ(V+E);implicit graph 通过 Adj(u) 函数动态计算 neighbors,几乎不保存 graph 本身。
  • BFS:从 source s 的 level 0 开始,逐层发现恰好距离为 i 的 vertices;frontier 保存上一层,next 构造下一层。
  • Shortest paths:level[v] 等于从 s 到 v 的最少 edges 数;parent pointers 组成一棵 shortest-path tree。
  • Complexity:每个 reachable vertex 和每条 edge 至多被处理一次,显式 adjacency-list graph 上运行时间为 O(V+E)。

目录

章节说明
Lecture 13:Graphs I:Breadth-First Searchgraph 基本定义与 graph search
Graph-search applicationsweb、network、puzzle 等应用
Graph representationsadjacency lists、implicit graphs、incidence lists
Breadth-first searchlevel、frontier 与 BFS algorithm
BFS 示例按层展开的过程
BFS 的复杂度vertex / edge 的一次性处理
Shortest pathslevels 与 parent tree 的 correctness
小结本讲要点

graph 由一组 vertices 和它们之间的 edges 组成:

text
G = (V, E)

其中:

text
V:vertices set,vertices 可以有任意 labels
E:edges set,每条 edge 是一对 vertices

pair 的类型决定 graph 类型:

text
ordered pair   (v, w) → directed edge v → w
unordered pair {v, w} → undirected edge v — w

例如,一个 undirected graph 可以有:

text
V = {a, b, c, d}
E = {{a,b}, {a,c}, {b,c}, {b,d}, {c,d}}

一个 directed graph 可以有:

text
V = {a, b, c}
E = {(a,c), (b,c), (c,b), (b,a)}

“Explore a graph” 可以包含不同目标:

text
从 start vertex 找到目标 vertex 的 path
访问 graph 的所有 vertices 或 edges
只访问从 start 可达的部分

graph search 的关键不只是“访问一次”,还包括如何记录已发现 vertices、如何组织待处理 frontier,以及如何从搜索结果恢复 path。

graph search 的应用非常广泛:

  • web crawling:搜索引擎如何发现 pages;
  • social networking:寻找朋友关系中的可达用户;
  • network broadcast routing:在 network 中传播消息;
  • garbage collection:从 roots 找到 reachable objects;
  • model checking:遍历 finite-state machine 的 states;
  • mathematical conjectures:枚举结构并检查性质;
  • puzzles and games:将 configuration 看成 graph 中的 vertex。

Pocket Cube configuration graph

考虑 2×2×2 Rubik’s cube。可以建立 configuration graph:

text
vertex:cube 的一个 possible state
edge:执行一个 basic move 后从一个 state 到另一个 state

因为 cube moves 可以反向执行,这个 graph 是 undirected。图的 diameter 称为 “God’s Number”,表示最坏 configuration 到 solved state 所需的最少 moves:

text
2×2×2 cube:11
3×3×3 cube:20
n×n×n cube:Θ(n² / log n)(讲义引用 2011 年结果)

BFS 从 solved state 出发,会先发现一步可达的 configurations,再发现两步可达但一步不可达的 configurations,继续向外扩展,直到最难的 states 也被覆盖。

2×2×2 cube 的 configuration 数量可以粗略计算为:

text
8! · 3^8 = 264,539,520

其中 8! 来自 8 个 cubelets 的任意位置排列,3^8 来自每个 cubelet 的 3 种 twists。去除 cube symmetries 后还要除以 24;考虑实际 reachable configurations 的 connected components 后还要进一步除以 3。

Graph representations

graph representation 是为 G=(V,E) 选择 data structure,使 neighbor iteration 和 edge access 高效。

Adjacency lists

最常用的表示是 adjacency lists:建立一个大小为 |V| 的 array 或 dictionary Adj,每个 vertex u 对应一个 neighbors list:

text
Adj[u] = {v ∈ V | (u, v) ∈ E}

对于 directed graph,Adj[u] 保存从 u 出发的 outgoing edges;对于 undirected graph,每条 edge 会出现在两个 endpoints 的 lists 中。

text
Adj = {
    a: [b, c],
    b: [a, c, d],
    c: [a, b, d],
    d: [b, c]
}

在 Python 中,可以使用 dictionary of lists / sets;vertex 只需要是 hashable object,例如 integer、tuple 或 string。

adjacency-list representation 的 space 为:

text
Θ(V + E)

对 undirected graph,edge 在两个 lists 中出现,所以常数因子是 2,但 asymptotic bound 仍然是 Θ(V+E)。它的优势包括:

  • 可以在同一组 vertices 上保存多个不同 graph;
  • sparse graph 不需要分配 V×V 的 adjacency matrix;
  • 遍历 vertex 的 neighbors 很直接。

Implicit graphs

某些 graph 不需要显式保存 edges。可以把:

text
Adj(u)

实现成一个函数,根据 vertex u 动态计算 neighbors。例如 Rubik’s cube graph 中,Adj(state) 可以现场生成所有合法 basic moves 的结果。

这种表示几乎不需要保存 graph 的 space:

text
显式 graph:保存 vertices / edges
implicit graph:保存状态表示与 neighbor-generation function

代价是每次调用 Adj(u) 都可能需要计算,且 graph 可能非常大甚至无法完整枚举。

Object-oriented representation

也可以为每个 vertex 建立 object:

python
u.neighbors = list_of_neighbors

这本质上仍然是 adjacency lists,只是把 adjacency information 放在 vertex object 中;对 implicit graph,则可以把 neighbors 作为动态 method。

Incidence lists

如果 edge 本身携带大量 data,可以把 edges 也建成 objects:

text
edge e:
    e.a = source vertex
    e.b = destination vertex

u.edges = outgoing edge objects

incidence-list 的优势是可以直接在 edge object 上保存 weight、capacity、label 等 edge data,不必通过额外 key 去查询。

BFS 从 source vertex s 出发,按距离一层一层探索 graph:

text
level 0 = {s}
level i = 能通过恰好 i 条 edges 从 s 到达、且不能用更少 edges 到达的 vertices

直观上:

text
level 0 → level 1 → level 2 → ... → last level

为了构造 level i,只需从 level i-1 的 vertices 尝试所有 outgoing edges,并忽略之前 levels 已经发现的 vertices。

Frontier-based BFS

MIT 讲义使用 frontier list 表示上一层,用 next list 构造下一层:

python
def bfs(V, Adj, s):
    level = {s: 0}
    parent = {s: None}
    i = 1
    frontier = [s]

    while frontier:
        next_frontier = []

        for u in frontier:
            for v in Adj[u]:
                if v not in level:
                    level[v] = i
                    parent[v] = u
                    next_frontier.append(v)

        frontier = next_frontier
        i += 1

    return level, parent

这里 level 同时充当 visited set:一个 vertex 一旦被写入 level,以后就不会再次加入 next_frontier。parent[v] 记录第一次发现 v 时从哪个 vertex 走过来。

CLRS 常用 queue-based implementation:frontier list 的实现细节不同,但 invariant 相同——queue 中的 vertices 按 nondecreasing distance 顺序处理。

BFS 示例

考虑 source s,假设 graph 的探索得到:

text
frontier₀ = {s}
frontier₁ = {a, x}
frontier₂ = {z, d, c}
frontier₃ = {f, v}

当处理 frontier₁={a,x} 时,x、c、d 可能已经通过另一条 path 被发现,因此不会重复加入下一层。关键规则是:

python
if v not in level:
    level[v] = i

第一次发现 vertex 的那条 path 就确定了它的最短 edge count;后续遇到同一 vertex 的 edges 只会产生重复候选,不需要改变 parent。

BFS 的 parent pointers 形成一棵 rooted tree:

text
parent[s] = None
每个其他 reachable vertex 恰有一个 parent
parent[v] 位于比 v 更早的 level

BFS 的复杂度

每个 vertex 只会进入 next_frontier 一次,因为一旦设置 level[v],后续检查都会失败。因此:

  1. 每个 reachable vertex 的 Adj[v] loop 只执行一次;
  2. 对每个 vertex,所有 outgoing edges 只扫描一次;
  3. 每条 directed edge 只被处理一次。

所以 directed graph 的时间是:

text
∑_{v∈V} |Adj[v]| = |E|

再加上 vertices、dictionary lookups 和 frontier 管理,得到:

text
O(V + E)

对于 undirected graph,每条 edge 在两个 adjacency lists 中出现,所以扫描总量是 2|E|,仍然是:

text
O(V + E)

如果只关心从 s 可达的 component,实际工作量可以写成 O(V_reachable + E_reachable);如果还要列出所有 unreachable vertices,则完整运行时间为 O(V+E)。

Shortest paths

对于每个 vertex v,从 s 出发的 fewest-edge distance 是:

text
level[v],如果 v 被 BFS 发现
∞,如果 v 没有被发现,即从 s 不可达

为什么 BFS 的 level 是 shortest distance?

Upper bound

当 BFS 在 level i-1 处理某个 u,发现 neighbor v 时,已经存在一条从 s 到 u 的 path,长度为 i-1;再加 edge (u,v),得到一条长度为 i 的 path:

text
distance(s, v) ≤ level[v] = i

No shorter path

如果存在一条长度小于 i 的 path 到达 v,那么沿着这条 path 从 s 向外走,在不晚于 level i-1 时就会处理到 v 的某个 predecessor,并发现 v。这样 v 应该更早被放入某个 level,与 level[v]=i 矛盾。

因此不存在少于 i 条 edges 的 path:

text
distance(s, v) ≥ level[v]

结合 upper bound:

text
distance(s, v) = level[v]

恢复 shortest path

若要找到从 s 到 v 的 path,可以不断沿 parent pointers 回溯:

text
v → parent[v] → parent[parent[v]] → ... → s

然后将这个序列 reverse。因为每个 parent 都位于前一个 level,这条 path 恰好包含 level[v] 条 edges,是一条 shortest path。

小结

graph search 的效率首先取决于 graph representation。adjacency lists 对 sparse graph 提供 Θ(V+E) space;implicit graph 通过 Adj(u) 动态计算 neighbors,适合巨大 configuration spaces。

BFS 从 source s 开始维护 levels 和 frontiers,每次只从上一层构造下一层,并用 visited / level 防止重复发现。每个 vertex 和 edge 至多被处理一次,因此运行时间是 O(V+E)。更重要的是,BFS 的 level[v] 正是从 s 到 v 的 fewest-edge distance,而 parent pointers 构成 shortest-path tree。

参考资料

← 返回列表
← 上一篇 Square Roots、Newton’s Method 与 High-Precision Division 下一篇 → Depth-First Search、Cycle Detection 与 Topological Sort

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论