Introduction

Breadth-first search (BFS) explores a graph level by level from a source ss: it visits every vertex at distance kk before any vertex at distance k+1k+1. The search builds a BFS tree of shortest paths in the unweighted sense (fewest edges) and assigns each reachable vertex a distance d[v]=δ(s,v)d[v] = \delta(s,v).

BFS is the standard first algorithm on unweighted graphs: it needs a queue, runs in Θ(V+E)\Theta(V+E) time on an adjacency-list representation, and is the template for unweighted shortest paths and for bipartiteness testing. The same layer order underlies several standard applications: testing whether an undirected graph is bipartite, computing the eccentricity of a vertex, and (with two passes) the diameter of a tree. Weighted graphs need different algorithms; BFS is the unweighted base case that those algorithms generalise.

Prerequisites

Core concepts

Colours and distances

CLRS colours vertices white (undiscovered), grey (discovered but not fully explored) and black (fully explored). A single bit (discovered or not) suffices for correctness of distances; grey versus black is pedagogical.

On termination, for every vertex vv reachable from ss:

d[v]=δ(s,v),d[v] = \delta(s,v),

the fewest edges on any ss--vv path, and the predecessor π[v]\pi[v] yields a shortest path by walking π\pi to ss. Unreachable vertices keep d[v]=∞d[v] = \infty and π[v]=NIL\pi[v] = \mathrm{NIL}.

Layers

The vertices with d[v]=kd[v] = k form layer kk. Every edge of the BFS tree joins consecutive layers.

Edge rule. For every edge (u,v)(u,v) of a graph explored from ss, with uu reachable, d[v]≤d[u]+1d[v] \le d[u] + 1: when uu is dequeued, vv is either discovered then at distance d[u]+1d[u]+1 or was already discovered at a smaller or equal distance.

  • Undirected graph. Applying the rule in both directions gives ∣d[u]−d[v]∣≤1|d[u] - d[v]| \le 1. A non-tree edge joins two vertices in the same layer or in adjacent layers. The BFS forest has tree edges and cross edges only, no back or forward edges.
  • Directed graph. Only d[v]≤d[u]+1d[v] \le d[u] + 1 holds. An edge may point back any number of layers (d[v]d[v] much smaller than d[u]d[u]) but never forward by two or more layers. There are no forward edges.

Algorithms and pseudocode

Pseudocode uses adjacency lists Adj[u], <- for assignment and a FIFO queue Q.

Text
BFS(G, s)
 1  for each vertex u in G.V - {s}
 2      u.color <- WHITE
 3      u.d <- infinity
 4      u.pi <- NIL
 5  s.color <- GREY
 6  s.d <- 0
 7  s.pi <- NIL
 8  Q <- empty queue
 9  ENQUEUE(Q, s)
10  while Q is not empty
11      u <- DEQUEUE(Q)
12      for each v in Adj[u]
13          if v.color = WHITE then
14              v.color <- GREY
15              v.d <- u.d + 1
16              v.pi <- u
17              ENQUEUE(Q, v)
18      u.color <- BLACK

Input. Graph G=(V,E)G=(V,E) (directed or undirected) and source s∈Vs \in V.

Output. Attributes dd and π\pi on VV; the BFS tree edges are {(π[v],v):π[v]≠NIL}\{( \pi[v], v) : \pi[v] \ne \mathrm{NIL}\}.

Time / space. Each vertex is enqueued at most once and each adjacency list is scanned once: Θ(V+E)\Theta(V+E) on adjacency lists. On an adjacency matrix the neighbour scan costs Θ(V2)\Theta(V^2). Extra space Θ(V)\Theta(V) for colours, distances, predecessors and the queue.

Edge cases. Isolated source: d[s]=0d[s]=0, all others ∞\infty. Self-loops and parallel edges do not change distances. In a disconnected undirected graph, BFS from ss reaches only ss's component; a full covering needs a loop over unused sources (as in DFS).

How BFS uses the queue

Queued grey vertices await processing; the currently scanned grey vertex has already left the queue and becomes black only after its adjacency scan finishes. Newly discovered neighbours are enqueued at the back; the next vertex to explore is taken from the front. That FIFO discipline is exactly what forces layer kk to finish before layer k+1k+1 begins. Replacing the queue by a stack yields a form of DFS and destroys the distance guarantee.

Space for the queue is O(V)O(V) in the worst case (for example a star: the centre discovers all leaves before any leaf is dequeued). The queue contains vertices from at most two consecutive distance layers. If the maximum reachable layer width is WW, its peak size is at least WW and at most 2W2W, hence O(V)O(V), not necessarily exactly WW. For example, let the source discover a,b,ca,b,c, and let aa discover d,e,fd,e,f. Both nontrivial layers have width 3, but after exploring aa the queue is b,c,d,e,fb,c,d,e,f, of size 5.

Mathematical explanation

Correctness sketch

A standard inductive argument (CLRS 3e, Section 22.2) shows that when a vertex vv is first discovered from uu, one has d[v]=d[u]+1=δ(s,v)d[v] = d[u]+1 = \delta(s,v). The queue always holds vertices of at most two consecutive distances, so layers are processed in order.

Bipartiteness

An undirected graph is bipartite if and only if it has no odd cycle. Run BFS from each undiscovered source and try to 2-colour by layer parity (d[v] mod 2d[v] \bmod 2). Because every edge joins equal or adjacent layers, the colouring fails exactly when some edge joins two vertices of the same layer. Such an edge (u,v)(u,v) closes an odd cycle: the tree paths from uu and from vv up to their lowest common ancestor have equal length, so together with the edge they form a cycle of odd length. Time still Θ(V+E)\Theta(V+E).

Counting shortest paths

BFS also counts fewest-edge paths. Before BFS, initialize cnt[v]=0cnt[v]=0 for every vertex, then set cnt[s]=1cnt[s]=1. When uu is dequeued, for each neighbour vv with d[v]=d[u]+1d[v] = d[u] + 1 (just discovered or discovered earlier in this layer), add cnt[u]cnt[u] to cnt[v]cnt[v]. Because a whole layer is dequeued before the next, cnt[u]cnt[u] is final when it is used.

Worked examples

Undirected graph on six vertices

Vertices {s,a,b,c,d,e}\{s,a,b,c,d,e\}. Edges: s−as{-}a, s−bs{-}b, a−ca{-}c, b−cb{-}c, b−db{-}d, c−ec{-}e, d−ed{-}e. Adjacency lists in alphabetical order within each list, with ss first in its own list written as a,ba,b.

BFS from ss:

StepDequeueDiscoverdd updates
startss (d=0d=0)
1ssaa (11), bb (11)
2aacc (22)
3bbdd (22)cc already grey
4ccee (33)
5ddee already grey
6ee

Distances: s:0s:0, a:1a:1, b:1b:1, c:2c:2, d:2d:2, e:3e:3. One BFS tree: edges s−as{-}a, s−bs{-}b, a−ca{-}c, b−db{-}d, c−ec{-}e.

Further facts on the same graph:

  • Bipartite. Every edge joins adjacent layers, so the parity colouring {s,c,d}\{s, c, d\} against {a,b,e}\{a, b, e\} is a valid 2-colouring. Adding the edge c−dc{-}d (both in layer 2) creates the odd cycle b,c,db, c, d of length 3.
  • Shortest-path counts. cnt=1,1,1cnt = 1, 1, 1 for s,a,bs, a, b; cnt[c]=cnt[a]+cnt[b]=2cnt[c] = cnt[a] + cnt[b] = 2; cnt[d]=cnt[b]=1cnt[d] = cnt[b] = 1; cnt[e]=cnt[c]+cnt[d]=3cnt[e] = cnt[c] + cnt[d] = 3. The three shortest ss--ee paths are s,a,c,es,a,c,e, s,b,c,es,b,c,e and s,b,d,es,b,d,e.
  • Which orders are BFS orders? Over every possible ordering of the adjacency lists, BFS from ss can output exactly three vertex orders: s,a,b,c,d,es,a,b,c,d,e, s,b,a,c,d,es,b,a,c,d,e and s,b,a,d,c,es,b,a,d,c,e. The order s,a,b,d,c,es,a,b,d,c,e is impossible: if aa is dequeued before bb, then aa discovers cc before bb discovers dd, so cc must precede dd. Within a layer, children inherit the order of their discoverers.
BFS layers and tree from source s
Figure 1. BFS from ss on the six-vertex undirected graph: layers d=0,1,2,3d=0,1,2,3 and tree edges s−as{-}a, s−bs{-}b, a−ca{-}c, b−db{-}d, c−ec{-}e.

Directed path versus shortcut

Vertices s,u,vs,u,v. Edges s→us\to u, u→vu\to v, s→vs\to v. BFS from ss discovers uu and vv at distance 1 (both from ss); the edge u→vu\to v is ignored for discovery. Distances δ(s,u)=1\delta(s,u)=1, δ(s,v)=1\delta(s,v)=1, not 2.

Non-tree edges in undirected BFS are cross edges

In the six-vertex example every non-tree edge is a cross edge: b−cb{-}c joins layers 1 and 2, and d−ed{-}e joins layers 2 and 3. No edge skips a layer, because a vertex two layers below uu would have been discovered from uu earlier. An edge inside a layer would show the graph is not bipartite, as explained under Bipartiteness.

Multi-source BFS

Enqueue several sources at once, each with d=0d=0. The resulting distances are to the nearest source, for example the distance from every cell of a grid to the closest exit. Time remains Θ(V+E)\Theta(V+E). Ordinary BFS from a new super-source joined by unit-weight edges to all sources gives distances one larger, so subtract one for every reachable original vertex. Directly initializing every source to distance zero avoids this adjustment.

0-1 BFS

Related material. When every edge weight is 0 or 1, a double-ended queue replaces Dijkstra's heap. Relax edge (u,v)(u,v) of weight ww; if d[u]+w<d[v]d[u] + w < d[v], set d[v]←d[u]+wd[v] \leftarrow d[u] + w and push vv to the front when w=0w = 0 and to the back when w=1w = 1. The deque always holds at most two distinct distance values, in order, so the run takes Θ(V+E)\Theta(V+E).

Directed example: s→as \to a (1), s→bs \to b (0), b→ab \to a (0), a→ta \to t (1), b→tb \to t (1). Plain BFS ignores the weights and reports aa one edge from ss. 0-1 BFS gives d[b]=0d[b] = 0, d[a]=0d[a] = 0 (via bb) and d[t]=1d[t] = 1. A vertex can enter the deque twice (here aa, first at the back with 1 and then at the front with 0), so a vertex popped again with an outdated distance is skipped.

Relationship to the shortest-path DAG

When all edge weights equal 1, on the vertices reachable from ss, the edges (u,v)(u,v) that satisfy d[v]=d[u]+1d[v] = d[u]+1 form the shortest-path DAG rooted at ss. The BFS tree is one spanning arborescence of that DAG. Different adjacency orders select different arborescences but the same distances.

Important properties and observations

  • d[v]d[v] is independent of adjacency-list order; the BFS tree (the π\pi values) may depend on that order.
  • BFS finds fewest-edge paths, not minimum-weight paths. For nonnegative weights use Dijkstra; for arbitrary weights use Bellman-Ford (Single-Source Shortest Paths).
  • In an unweighted graph (every edge weight 1), BFS computes exact shortest-path distances in linear time, faster than Dijkstra's O((V+E)lg⁡V)O((V+E)\lg V).
  • The height of the BFS tree from ss is the eccentricity of ss (its largest finite distance). The queue never holds vertices from more than two consecutive layers.
  • The diameter of a tree can be found with two BFS runs: BFS from any node to a farthest node aa, then BFS from aa to a farthest node bb; δ(a,b)\delta(a,b) is the diameter.

Common misconceptions.

  • "BFS needs a stack." That is DFS; BFS needs a queue.
  • "Grey and black are required for distances." Discovery (white to non-white) alone fixes dd.
  • "BFS works for negative weights." Weights are irrelevant to unweighted BFS; for weighted graphs BFS is correct only when every edge has the same positive weight (up to scaling).

GATE examination perspective

  • TRACE THE QUEUE. Questions give adjacency lists and ask for the dequeue order or the dd values.
  • TREE VERSUS NON-TREE. Identify which edges become π\pi edges under a stated list order.
  • LAYER EDGE. An undirected edge inside a layer means an odd cycle (not bipartite).
  • COMPLEXITY. Θ(V+E)\Theta(V+E) lists; Θ(V2)\Theta(V^2) matrix.
  • SHORTEST PATHS. State "fewest edges", not "minimum weight", unless all weights equal.
  • MULTI-SOURCE. Enqueuing several sources at distance 0 yields distance to the nearest source; state that clearly if the question offers several starts.
  • COMPONENT COVER. A single BFS does not visit other components; a loop over unused vertices is required for a full cover, exactly as in DFS.
  • VALID BFS ORDER. Check layer by layer: all of layer kk precedes layer k+1k+1, and the children of an earlier-dequeued vertex come before the children of a later one.
  • EDGE TYPES. Undirected BFS has only tree and cross edges with ∣d[u]−d[v]∣≤1|d[u]-d[v]| \le 1; directed BFS has no forward edges and d[v]≤d[u]+1d[v] \le d[u]+1 on every edge.
  • COUNT PATHS. Number of shortest paths: add cnt[u]cnt[u] into each neighbour one layer deeper.
  • 0/1 WEIGHTS. A deque (0-1 BFS) gives linear time; plain BFS is wrong once weights differ.

Summary

Sources

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009: Chapter 22, Section 22.2 (breadth-first search).

Next steps