How breadth-first search measures unweighted distance

Short answer: Breadth-first search expands a graph level by level from a source, using a queue. The first time a vertex is reached, the path that reached it is a shortest path in an unweighted graph, or in a graph whose edges all have the same positive cost. The running time is Θ(V+E) with an adjacency list. A later visit cannot improve that distance, so a vertex is marked when it is enqueued.


What the problem actually asks

Each edge steps one hop. Any path with k edges ends at a vertex k hops from the source, and no fewer hops can be discovered later, because the search emits vertices in nondecreasing hop count. The queue is what keeps that emission order: newly found vertices wait behind the rest of the current level.

Weighted edges break the story. A single heavy edge can be a worse route than several light ones. The first time the search reaches the vertex is then just the first time, not the cheapest time.


What the algorithm guarantees

On an unweighted graph the distance stored when a vertex is first enqueued is the minimum hop count, and the parent pointers form a shortest-path tree. Every vertex and every edge is processed a constant number of times, which is Θ(V+E) for an adjacency list and Θ(V²) for a dense matrix scanned naively. Extra memory is the queue, the colors or distances, and the parents, all Θ(V).

Marking a vertex when it is enqueued, rather than when it is dequeued, keeps it out of the queue a second time. Marking only on dequeue is still correct for unweighted graphs and can enqueue the same vertex once per incoming edge. The distances stay right either way. The early mark is the linear bound people quote.


The working steps

  1. Set the source distance to 0 and enqueue the source. Every other distance starts as infinite, meaning unseen.
  2. Dequeue u. For each neighbor v of u, if v is still unseen, set its distance to dist[u]+1, set its parent to u, mark it seen, and enqueue it.
  3. Continue until the queue is empty. Unseen vertices are not reachable from the source.
  4. The unique path of parent pointers from a reached vertex back to the source is a shortest path. Reconstruct it by walking parents.
  5. On a graph with equal positive edge weights, the same tree is a shortest-path tree and the hop count scales by that weight.

The first-visit rule is for unit or equal weights. Nonnegative unequal weights belong to Dijkstra, and a weight in {0, 1} belongs to 0-1 BFS. A negative weight can make a longer hop count cheaper, which this queue does not reconsider.


Approaches that look simpler and fail

Approach Why it fails when the first visit must be the shortest path
Unequal nonnegative weights The first path to a vertex can be one expensive edge. A later path of many cheap edges is shorter and will not replace the stored distance.
A stack instead of a queue That is depth-first order. The first time a vertex is seen can be a long detour, and the hop count is not minimal.
Re-enqueue a vertex whenever a neighbor offers a smaller hop count In an unweighted graph the first hop count is already minimal. Extra enqueues change the complexity and not the answer.
Stop at the first time the target is generated, on a weighted graph, and call it Dijkstra Generating the target during BFS is enough only for unit weights. Dijkstra may improve a vertex until the vertex is dequeued as settled.

Nonnegative weights belong to Dijkstra. Weights restricted to 0 and 1 belong to 0-1 BFS, which keeps a deque and still runs in linear time. Negative weights that may form a cycle belong to Bellman-Ford.


A working example

The Bash script and the Python script breadth-first search an unweighted graph and mark a vertex when it is enqueued. Edges are 0→1, 0→2, 1→2, 2→3. Both print distances 0 1 1 2.

adj=("1 2" "2" "3" "")
dist=(-1 -1 -1 -1)
dist[0]=0
q=(0)
head=0
while (( head < ${#q[@]} )); do
  u=${q[head]}
  head=$((head+1))
  for v in ${adj[u]}; do
    if (( dist[v] < 0 )); then
      dist[v]=$((dist[u]+1))
      q+=("$v")
    fi
  done
done
echo "${dist[*]}"
from collections import deque

adj = [[1, 2], [2], [3], []]
dist = [-1] * len(adj)
dist[0] = 0
q = deque([0])
while q:
    u = q.popleft()
    for v in adj[u]:
        if dist[v] < 0:
            dist[v] = dist[u] + 1
            q.append(v)
assert dist == [0, 1, 1, 2]
print(*dist)

Where it is used

Breadth-first search is the unweighted distance in a maze, a crawler frontier, and Cheney’s copying collector, which copies the object graph level by level. A weighted map uses Dijkstra. A mark stack in a garbage collector is the depth-first relative.


When you can drop this algorithm

Drop breadth-first search when edge weights are not identical. The level order is then only a traversal, not a distance. Keep it for unweighted shortest paths, connected components of an undirected graph, and any state graph whose edges are free unit steps.


Why this stays published

We publish this so a search for breadth-first search returns the first-enqueue distance and the unit-weight hypothesis it depends on. Breadth-first search computes hop-count distance in linear time because the queue emits vertices in order of increasing distance, and that reading requires unit weights.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

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