Introduction
Breadth-first search (BFS) explores a graph level by level from a source : it visits every vertex at distance before any vertex at distance . The search builds a BFS tree of shortest paths in the unweighted sense (fewest edges) and assigns each reachable vertex a distance .
BFS is the standard first algorithm on unweighted graphs: it needs a queue, runs in 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
- Graph Representations: adjacency lists and matrices.
- Queues: FIFO enqueue and dequeue.
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 reachable from :
the fewest edges on any -- path, and the predecessor yields a shortest path by walking to . Unreachable vertices keep and .
Layers
The vertices with form layer . Every edge of the BFS tree joins consecutive layers.
Edge rule. For every edge of a graph explored from , with reachable, : when is dequeued, is either discovered then at distance or was already discovered at a smaller or equal distance.
- Undirected graph. Applying the rule in both directions gives . 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 holds. An edge may point back any number of layers ( much smaller than ) 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.
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 <- BLACKInput. Graph (directed or undirected) and source .
Output. Attributes and on ; the BFS tree edges are .
Time / space. Each vertex is enqueued at most once and each adjacency list is scanned once: on adjacency lists. On an adjacency matrix the neighbour scan costs . Extra space for colours, distances, predecessors and the queue.
Edge cases. Isolated source: , all others . Self-loops and parallel edges do not change distances. In a disconnected undirected graph, BFS from reaches only '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 to finish before layer begins. Replacing the queue by a stack yields a form of DFS and destroys the distance guarantee.
Space for the queue is 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 , its peak size is at least and at most , hence , not necessarily exactly . For example, let the source discover , and let discover . Both nontrivial layers have width 3, but after exploring the queue is , of size 5.
Mathematical explanation
Correctness sketch
A standard inductive argument (CLRS 3e, Section 22.2) shows that when a vertex is first discovered from , one has . 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 (). 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 closes an odd cycle: the tree paths from and from up to their lowest common ancestor have equal length, so together with the edge they form a cycle of odd length. Time still .
Counting shortest paths
BFS also counts fewest-edge paths. Before BFS, initialize for every vertex, then set . When is dequeued, for each neighbour with (just discovered or discovered earlier in this layer), add to . Because a whole layer is dequeued before the next, is final when it is used.
Worked examples
Undirected graph on six vertices
Vertices . Edges: , , , , , , . Adjacency lists in alphabetical order within each list, with first in its own list written as .
BFS from :
| Step | Dequeue | Discover | updates |
|---|---|---|---|
| start | () | ||
| 1 | (), () | ||
| 2 | () | ||
| 3 | () | already grey | |
| 4 | () | ||
| 5 | already grey | ||
| 6 |
Distances: , , , , , . One BFS tree: edges , , , , .
Further facts on the same graph:
- Bipartite. Every edge joins adjacent layers, so the parity colouring against is a valid 2-colouring. Adding the edge (both in layer 2) creates the odd cycle of length 3.
- Shortest-path counts. for ; ; ; . The three shortest -- paths are , and .
- Which orders are BFS orders? Over every possible ordering of the adjacency lists, BFS from can output exactly three vertex orders: , and . The order is impossible: if is dequeued before , then discovers before discovers , so must precede . Within a layer, children inherit the order of their discoverers.

Directed path versus shortcut
Vertices . Edges , , . BFS from discovers and at distance 1 (both from ); the edge is ignored for discovery. Distances , , not 2.
Non-tree edges in undirected BFS are cross edges
In the six-vertex example every non-tree edge is a cross edge: joins layers 1 and 2, and joins layers 2 and 3. No edge skips a layer, because a vertex two layers below would have been discovered from 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 . The resulting distances are to the nearest source, for example the distance from every cell of a grid to the closest exit. Time remains . 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 of weight ; if , set and push to the front when and to the back when . The deque always holds at most two distinct distance values, in order, so the run takes .
Directed example: (1), (0), (0), (1), (1). Plain BFS ignores the weights and reports one edge from . 0-1 BFS gives , (via ) and . A vertex can enter the deque twice (here , 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 , the edges that satisfy form the shortest-path DAG rooted at . The BFS tree is one spanning arborescence of that DAG. Different adjacency orders select different arborescences but the same distances.
Important properties and observations
- is independent of adjacency-list order; the BFS tree (the 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 .
- The height of the BFS tree from is the eccentricity of (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 , then BFS from to a farthest node ; 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 .
- "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 values.
- TREE VERSUS NON-TREE. Identify which edges become edges under a stated list order.
- LAYER EDGE. An undirected edge inside a layer means an odd cycle (not bipartite).
- COMPLEXITY. lists; 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 precedes layer , 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 ; directed BFS has no forward edges and on every edge.
- COUNT PATHS. Number of shortest paths: add 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
- 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).