Discrete Mathsfor Engineers

Structures, proofs, and intuition

EN | PT

Breadth-First Search (BFS)

Part 3 — The Algorithm (CLRS Pseudocode)

Series: Breadth-First Search (BFS) Part 3 of 8

3. The Algorithm


Roadmap (what you will learn in this part):
  1. Define the formal model used by BFS
  2. Specify the state stored at each vertex
  3. Present the CLRS pseudocode
  4. Explain why the predecessor pointers form a tree
  5. Analyze the time complexity

In this section, we formalize Breadth-First Search (BFS) using the classical presentation from Introduction to Algorithms (CLRS).

We move from intuition to structure: precise state, precise steps, and the guarantees that follow.

3.1 Objective

Given a graph G and a source vertex s, BFS explores the graph in increasing distance from s.

In unweighted graphs, this means BFS computes shortest-path distances (by number of edges) from s to every reachable vertex.

3.2 Formal Model

Let:

  • G = (V, E) be a graph
  • s ∈ V be the source vertex
Assumption: BFS uses an adjacency list Adj[u] to iterate neighbors efficiently.

3.3 Vertex State

Each vertex v ∈ V stores:

  • color[v]WHITE, GRAY, BLACK
  • d[v] → distance from the source
  • π[v] → predecessor
Color Meaning
WHITE Not discovered yet
GRAY Discovered but not fully explored
BLACK Fully explored

This coloring enforces structure and prevents revisiting vertices.

3.4 CLRS Pseudocode — BFS

BFS(G, s):

    for each vertex u in V[G]:
        color[u] = WHITE
        d[u] = ∞
        π[u] = NIL

    color[s] = GRAY
    d[s] = 0
    π[s] = NIL

    Q = empty queue
    ENQUEUE(Q, s)

    while Q is not empty:
        u = DEQUEUE(Q)

        for each v in Adj[u]:
            if color[v] == WHITE:
                color[v] = GRAY
                d[v] = d[u] + 1
                π[v] = u
                ENQUEUE(Q, v)

        color[u] = BLACK
Key idea: BFS is “FIFO by design”. The queue forces a layer-by-layer exploration.

3.5 Structural Guarantees

The algorithm guarantees:

  1. Vertices are explored in increasing distance order.
  2. The first time we reach a vertex, we have found a shortest path (in unweighted graphs).
  3. The predecessor pointers π[v] form a BFS tree.

3.6 Why This Produces a Tree

Every vertex (except the source) receives exactly one predecessor.

Therefore:

  • The predecessor relation defines a tree.
  • If n vertices are reachable, the BFS tree has exactly n − 1 edges.
Connection to Part 2: A tree is connected and acyclic, so it must have exactly n − 1 edges.

3.7 Time Complexity

If adjacency lists are used:

O(|V| + |E|)

Each vertex is enqueued at most once. Each edge is examined at most twice (undirected case).

Next: Part 4 — Correctness Proof

Now that we have the algorithm in precise form, the next step is to justify it formally. In Part 4, we prove correctness using invariants: why distances are minimal, and why the exploration order is guaranteed.