TExcelTAD
Home › Graph Algorithms › Breadth-First Search

Breadth-First Search

Drop a stone into a pond and the ripples reach nearby points first, farther points later. Breadth-first search (BFS) explores a graph the same way. From a source vertex ss it first discovers every neighbour of ss, then every vertex two edges away, then three, and so on, in waves. The order is enforced by a first-in, first-out queue: vertices leave the queue in the order they were discovered. As a by-product BFS computes, for every vertex, the smallest number of edges on a path from ss, and a tree of shortest paths. It runs in O(V+E)O(V + E) time and is the building block of many algorithms in this course, including Edmonds-Karp for maximum flow. The DSA course shows a first version; here the algorithm records distances and predecessors, and the next lesson proves the distances right.

The algorithm

Every vertex vv gets two attributes: v.dv.d, its distance from ss as BFS discovered it, and v.πv.\pi, the vertex from which it was discovered (its predecessor, or parent). A vertex with v.d=∞v.d = \infty has not been discovered yet.

text
BFS(G, s)
1  for each vertex v in G.V
2      v.d = infinity;  v.pi = NIL
3  s.d = 0
4  Q = a queue containing only s
5  while Q is not empty
6      u = DEQUEUE(Q)
7      for each v in G.Adj[u]                // in alphabetical order in this course
8          if v.d == infinity                // v is seen for the first time
9              v.d = u.d + 1
10             v.pi = u
11             ENQUEUE(Q, v)

Each vertex is in one of three states: undiscovered (d=∞d = \infty), in the queue (discovered, its neighbours not yet examined), or finished (dequeued and scanned). Textbooks often paint these white, gray and black; the animation paints the queued vertices as the frontier.

The Python version prints the same steps as the animation: each dequeue with the queue that remains, and each newly discovered vertex with the distance it receives.

python · try it yourself
from collections import deque

edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("C", "E"), ("D", "F"), ("E", "F"), ("E", "G"), ("F", "H"), ("G", "H")]
adj = {v: [] for v in "ABCDEFGH"}
for u, v in edges:
    adj[u].append(v)
    adj[v].append(u)
for v in adj:
    adj[v].sort()

def bfs(adj, s):
    d = {v: None for v in adj}          # None plays the role of infinity
    pi = {v: None for v in adj}
    d[s] = 0
    q = deque([s])
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        print(f"dequeue {u} (d = {d[u]}), queue now {list(q)}")
        for v in adj[u]:
            if d[v] is None:
                d[v], pi[v] = d[u] + 1, u
                q.append(v)
                print(f"  discover {v}: d = {d[v]}, parent {u}, queue {list(q)}")
    return d, pi, order

d, pi, order = bfs(adj, "A")
print("visit order:", " -> ".join(order))
print("distances:  ", d)
print("parents:    ", pi)
dequeue A (d = 0), queue now []
  discover B: d = 1, parent A, queue ['B']
  discover C: d = 1, parent A, queue ['B', 'C']
dequeue B (d = 1), queue now ['C']
  discover D: d = 2, parent B, queue ['C', 'D']
dequeue C (d = 1), queue now ['D']
  discover E: d = 2, parent C, queue ['D', 'E']
dequeue D (d = 2), queue now ['E']
  discover F: d = 3, parent D, queue ['E', 'F']
dequeue E (d = 2), queue now ['F']
  discover G: d = 3, parent E, queue ['F', 'G']
dequeue F (d = 3), queue now ['G']
  discover H: d = 4, parent F, queue ['G', 'H']
dequeue G (d = 3), queue now ['H']
dequeue H (d = 4), queue now []
visit order: A -> B -> C -> D -> E -> F -> G -> H
distances:   {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3, 'G': 3, 'H': 4}
parents:     {'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D', 'G': 'E', 'H': 'F'}

The distances come out in waves: AA at 0; B,CB, C at 1; D,ED, E at 2; F,GF, G at 3; HH at 4. Vertex DD is adjacent to both BB and CC, and BFS discovers it from BB, the first of the two to leave the queue. When CC scans its neighbours later, DD is no longer undiscovered and is left alone. That one test on line 8 is what makes the parent pointers form a tree.

Running time

Initialization costs Θ(V)\Theta(V). After that, a vertex is enqueued only when its dd changes from ∞\infty, which happens at most once, so each vertex is enqueued and dequeued at most once: O(V)O(V) queue operations, each O(1)O(1). The inner loop scans the adjacency list of a vertex when it is dequeued, so every list is scanned at most once, and the total length of all lists is Θ(E)\Theta(E). This is aggregate analysis: the inner loop can be long for one vertex and short for another, but summed over all vertices it runs O(E)O(E) times. The total is O(V+E)O(V + E), linear in the size of the adjacency-list representation.

With an adjacency matrix, line 7 scans a whole row of VV cells for each dequeued vertex, and the bound becomes O(V2)O(V^2).

The program checks the count on grid graphs of growing size, where E≈2VE \approx 2V: the number of adjacency-list entries examined is exactly 2E2E when every vertex is reachable, because each undirected edge appears in two lists.

python · try it yourself
from collections import deque

def grid(rows, cols):
    adj = {}
    for r in range(rows):
        for c in range(cols):
            adj[(r, c)] = [(r + dr, c + dc) for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1))
                           if 0 <= r + dr < rows and 0 <= c + dc < cols]
    return adj

def bfs_counts(adj, s):
    d = {s: 0}
    q = deque([s])
    dequeues = looks = 0
    while q:
        u = q.popleft()
        dequeues += 1
        for v in adj[u]:
            looks += 1
            if v not in d:
                d[v] = d[u] + 1
                q.append(v)
    return dequeues, looks, max(d.values())

print(f"{'grid':>8} {'V':>6} {'E':>6} {'dequeues':>9} {'list entries':>13} {'farthest':>9}")
for k in [5, 10, 20, 40]:
    adj = grid(k, k)
    E = sum(len(a) for a in adj.values()) // 2
    deq, looks, far = bfs_counts(adj, (0, 0))
    print(f"{k:>3} x {k:<3} {len(adj):>6} {E:>6} {deq:>9} {looks:>13} {far:>9}")
    grid      V      E  dequeues  list entries  farthest
  5 x 5       25     40        25            80         8
 10 x 10     100    180       100           360        18
 20 x 20     400    760       400          1520        38
 40 x 40    1600   3120      1600          6240        78

Doubling the side quadruples VV and EE, and the work grows by exactly the same factor. The farthest cell from a corner is 2(k−1)2(k - 1) steps away, the Manhattan distance to the opposite corner. The practice problem Shortest Path in a Grid asks for exactly this kind of distance in a grid with walls, and Word Ladder runs BFS on a graph whose vertices are words.

In C++

The C++ version stores vertices as numbers 00 to V−1V - 1 and uses std::queue. It runs BFS from AA on the graph of the animation and prints the same visit order, distances and parents.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <queue>
#include <string>
#include <utility>
#include <vector>

int main() {
    const std::string names = "ABCDEFGH";
    const int n = static_cast<int>(names.size());
    std::vector<std::pair<char, char>> edges = {{'A','B'}, {'A','C'}, {'B','D'}, {'C','D'}, {'C','E'},
                                                {'D','F'}, {'E','F'}, {'E','G'}, {'F','H'}, {'G','H'}};
    std::vector<std::vector<int>> adj(n);
    for (auto [a, b] : edges) {
        adj[a - 'A'].push_back(b - 'A');
        adj[b - 'A'].push_back(a - 'A');
    }
    for (auto& list : adj) std::sort(list.begin(), list.end());

    std::vector<int> d(n, -1), pi(n, -1);               // -1 = infinity / NIL
    std::queue<int> q;
    d[0] = 0;
    q.push(0);
    std::string order;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        order += names[u];
        for (int v : adj[u])
            if (d[v] == -1) {
                d[v] = d[u] + 1;
                pi[v] = u;
                q.push(v);
            }
    }
    std::printf("visit order: %s\n", order.c_str());
    for (int v = 0; v < n; ++v)
        std::printf("%c: d = %d, parent %c\n", names[v], d[v], pi[v] < 0 ? '-' : names[pi[v]]);
}
visit order: ABCDEFGH
A: d = 0, parent -
B: d = 1, parent A
C: d = 1, parent A
D: d = 2, parent B
E: d = 2, parent C
F: d = 3, parent D
G: d = 3, parent E
H: d = 4, parent F

BFS on directed and disconnected graphs

Nothing in the pseudocode assumes the edges are undirected. On a directed graph, Adj[u]\textit{Adj}[u] lists the heads of the edges leaving uu, and BFS follows edges only forwards. Vertices that cannot be reached from ss keep d=∞d = \infty: BFS from one source explores exactly the set of vertices reachable from it. To visit everything, run BFS again from each vertex that is still undiscovered; on an undirected graph each run then finds one connected component.

python · try it yourself
from collections import deque

adj = {"A": ["B"], "B": ["C", "D"], "C": ["A"], "D": [], "E": ["D", "F"], "F": []}   # directed
def bfs(s, d):
    d[s] = 0
    q = deque([s])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in d:
                d[v] = d[u] + 1
                q.append(v)

from_a = {}
bfs("A", from_a)
print("reachable from A:", from_a)
print("not reachable from A:", [v for v in adj if v not in from_a])
from_e = {}
bfs("E", from_e)
print("reachable from E:", from_e)
reachable from A: {'A': 0, 'B': 1, 'C': 2, 'D': 2}
not reachable from A: ['E', 'F']
reachable from E: {'E': 0, 'D': 1, 'F': 1}

Following arrows, AA reaches BB, CC and DD but not EE or FF; from EE only DD and FF are reachable. Reachability in a directed graph is not symmetric: EE reaches DD, but DD reaches nothing.

Test yourself

BFS runs from ss on a connected undirected graph. How many times is each vertex enqueued?

  1. Once per incident edge
  2. Exactly once
  3. At most twice
  4. Once per level

Why is BFS O(V+E)O(V + E) and not O(V⋅E)O(V \cdot E), even though it has a loop over neighbours inside a loop over vertices?

  1. Because the queue is a linked list
  2. Because each adjacency list is scanned only once, when its vertex is dequeued, so the inner loop runs O(E)O(E) times in total
  3. Because most vertices have degree 1
  4. Because BFS stops at the first leaf

In the animation's graph, DD is adjacent to both BB and CC. Which becomes its parent, and why?

  1. CC, because it is closer to AA
  2. BB, because BB is dequeued before CC and discovers DD first
  3. Both: DD gets two parents
  4. Whichever edge was added last