Why Does BFS Find Shortest Paths? A Layer-by-Layer Proof

☰ 开始北极星测评

Python DSA Notes

Why Does BFS Find Shortest Paths? A Layer–by–Layer Proof

See how a FIFO queue preserves distance layers in an unweighted graph.

Python DSA 笔记

为什么 BFS 能找到最短路径?从分层搜索到正确性证明

理解 FIFO 队列如何维持无权图的距离层级。

分享这篇文章

复制链接、使用手机分享、用微信扫码,或通过邮件发送。

邮箱

Many students learn the BFS template before they understand its guarantee. The guarantee does not come from “using a queue” alone. It comes from the way a FIFO queue preserves distance layers.

The Setting

BFS finds shortest paths when every edge has the same cost. This includes unweighted graphs, grids where every move costs one step, and page-choice graphs where every choice counts once.

If edges have different nonnegative weights, use Dijkstra's algorithm instead. If negative weights are allowed, a different method is required.

Distance Layers

Let the source be s.

  • Layer 0 contains s.
  • Layer 1 contains vertices reachable by one edge.
  • Layer 2 contains vertices whose shortest route uses two edges.
  • Layer k contains vertices at shortest distance k.

BFS finishes discovering the current layer before it processes the next one. That is the heart of the algorithm.

Why FIFO Matters

Suppose a vertex u at distance k is removed from the front. Every newly discovered neighbour receives distance k + 1 and goes to the back. All vertices already waiting in front have distance at most k + 1.

The queue therefore never processes a later distance layer before an earlier one. A stack would not preserve this order, which is why ordinary DFS cannot guarantee an unweighted shortest path.

The First-Discovery Rule

Mark a vertex visited when you enqueue it. Its first discovery comes from the earliest possible layer, so the assigned distance is already optimal.

Marking only when dequeuing allows several parents to enqueue the same vertex. It may not change the final answer, but it wastes work and makes parent tracking harder.

A Small Trace

S → A, B
A → C
B → D
C → T
D → T

The queue evolves as follows:

[S]
[A, B]
[B, C]
[C, D]
[D, T]

Distances are assigned as 0, 1, 1, 2, 2, 3. When T is first discovered, every possible route with fewer than three edges has already been considered.

Python Template

from collections import deque

def bfs(graph, source):
    distance = [-1] * len(graph)
    parent = [-1] * len(graph)
    distance[source] = 0
    queue = deque([source])

    while queue:
        node = queue.popleft()
        for neighbour in graph[node]:
            if distance[neighbour] == -1:
                distance[neighbour] = distance[node] + 1
                parent[neighbour] = node
                queue.append(neighbour)

    return distance, parent

distance[v] == -1 doubles as the unvisited check. parent lets us reconstruct an actual shortest path, not only its length.

C++ Template

vector<int> distance(n, -1), parent(n, -1);
queue<int> q;
distance[source] = 0;
q.push(source);

while (!q.empty()) {
    int node = q.front();
    q.pop();

    for (int neighbour : graph[node]) {
        if (distance[neighbour] == -1) {
            distance[neighbour] = distance[node] + 1;
            parent[neighbour] = node;
            q.push(neighbour);
        }
    }
}

Correctness Proof

We prove by induction on the layer number that every vertex in layer k receives its true shortest distance k.

Base case: The source is in layer 0 and is assigned distance 0, which is correct.

Inductive step: Assume all vertices through layer k have correct distances. Any vertex first discovered from a layer-k vertex receives k + 1, so a route of that length exists. If a shorter route existed, its predecessor would be in a layer earlier than k, and the vertex would already have been discovered. That is a contradiction.

Therefore every first-assigned BFS distance is a shortest distance.

Complexity

With an adjacency list, each vertex is enqueued once and each edge is examined once.

  • Time: O(V + E)
  • Space: O(V + E) including the graph

常见错误

  • Applying BFS to differently weighted edges.
  • Marking visited on dequeue instead of enqueue.
  • Mixing “number of edges” with “number of vertices on the path.”
  • Stopping at discovery when the surrounding task still requires full reachability information.
  • Using a list front-removal operation with linear cost instead of a real queue/deque.

Connection to CCC 2018 J5

In Choose your own path, pages are vertices and choices are equal-cost directed edges. BFS's first ending is shortest because endings are encountered in distance-layer order. The source distance is initialized to 1 only because that problem counts pages rather than edges.

复盘

  1. What exact property would break if we replaced the queue with a stack?
  2. Why is the first assigned distance final?
  3. When should BFS be replaced by Dijkstra?

Sources

  • Pythoncollections.deque: https://docs.python.org/3/library/collections.html#collections.deque
  • CEMC 2018 Junior problem set: https://cemc.uwaterloo.ca/sites/default/files/documents/2018/2018CCCJrProblemSet.html

Read Next

很多同学先记住 BFS 模板,之后才开始理解它为什么正确。BFS 的保证并不只是因为“用了队列”,而是因为 FIFO 队列能够维持距离层级。

适用范围

当每条边代价相同时,BFS 可以寻找最短路径。这包括无权图、每步代价为 1 的网格,以及每次选择都算一步的故事页面图。

如果边权不同但非负,应使用 Dijkstra;如果允许负权,则需要其他算法。

距离分层

设起点为 s:第 0 层只有起点;第 1 层是一步可达节点;第 2 层是最短需要两步的节点;第 k 层就是最短距离为 k 的节点。

BFS 会先发现完当前层,再处理下一层。这就是算法的核心。

为什么必须是 FIFO?

假设距离为 k 的节点 u 从队首取出。它新发现的邻居距离为 k + 1,并被放到队尾。此时排在它前面的节点距离不会超过 k + 1。

因此,队列不会让更远层级抢在更近层级之前处理。栈无法保持这个顺序,所以普通 DFS 不保证无权最短路径。

首次发现原则

节点入队时就应标记。它第一次被发现时来自最早可能到达的层级,因此此时设置的距离已经是最优距离。

如果等到出队才标记,多个父节点可能重复把同一节点加入队列。答案未必错误,但会浪费工作,也让路径还原更混乱。

一个小例子

S → A, B
A → C
B → D
C → T
D → T
[S]
[A, B]
[B, C]
[C, D]
[D, T]

距离依次为 0, 1, 1, 2, 2, 3。当 T 第一次被发现时,少于三条边的所有可能路径都已经处理过,因此距离 3 就是最短距离。

Python 模板

from collections import deque

def bfs(graph, source):
    distance = [-1] * len(graph)
    parent = [-1] * len(graph)
    distance[source] = 0
    queue = deque([source])

    while queue:
        node = queue.popleft()
        for neighbour in graph[node]:
            if distance[neighbour] == -1:
                distance[neighbour] = distance[node] + 1
                parent[neighbour] = node
                queue.append(neighbour)

    return distance, parent

distance[v] == -1 同时承担未访问标记;parent 可以还原一条具体最短路径,而不仅是长度。

C++ 模板

vector<int> distance(n, -1), parent(n, -1);
queue<int> q;
distance[source] = 0;
q.push(source);

while (!q.empty()) {
    int node = q.front();
    q.pop();

    for (int neighbour : graph[node]) {
        if (distance[neighbour] == -1) {
            distance[neighbour] = distance[node] + 1;
            parent[neighbour] = node;
            q.push(neighbour);
        }
    }
}

正确性证明

我们对层数 k 进行归纳,证明第 k 层的每个节点都会得到真实最短距离 k。

基础情况: 起点位于第 0 层,距离设为 0,显然正确。

归纳步骤: 假设第 k 层及之前的节点距离均正确。由第 k 层首次发现的邻居会得到 k + 1,说明确实存在这么长的路径。若存在更短路径,它的前驱应处于更早层级,该节点本应更早被发现,产生矛盾。

所以 BFS 第一次设置的距离就是最短距离。

复杂度

使用邻接表时,每个节点入队一次,每条边检查一次,时间为 O(V + E),包含图本身的空间为 O(V + E)。

常见错误

与本周真题的联系

在 Choose your own path 中,页面是节点,选择是等代价的有向边。BFS 按距离层遇到结局,因此第一个结局最短;题目把起点距离设为 1,只是因为它计算页面数量而不是边数。

复习

  1. 如果把队列换成栈,哪项性质会被破坏?
  2. 为什么第一次设置的距离就是最终答案?
  3. 什么情况下应该改用 Dijkstra?

来源及延伸阅读

  • Pythoncollections.deque: https://docs.python.org/3/library/collections.html#collections.deque
  • CEMC 2018 Junior problem set: https://cemc.uwaterloo.ca/sites/default/files/documents/2018/2018CCCJrProblemSet.html

延伸阅读

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈
Back to Python DSA Notes
返回Python DSA 笔记

发表评论

Your email address will not be published. Required fields are marked *

滚动至顶部