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 it first discovers every neighbour of , 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 , and a tree of shortest paths. It runs in 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 gets two attributes: , its distance from as BFS discovered it, and , the vertex from which it was discovered (its predecessor, or parent). A vertex with has not been discovered yet.
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 (), 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.
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: at 0; at 1; at 2; at 3; at 4. Vertex is adjacent to both and , and BFS discovers it from , the first of the two to leave the queue. When scans its neighbours later, 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 . After that, a vertex is enqueued only when its changes from , which happens at most once, so each vertex is enqueued and dequeued at most once: queue operations, each . 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 . This is aggregate analysis: the inner loop can be long for one vertex and short for another, but summed over all vertices it runs times. The total is , linear in the size of the adjacency-list representation.
With an adjacency matrix, line 7 scans a whole row of cells for each dequeued vertex, and the bound becomes .
The program checks the count on grid graphs of growing size, where : the number of adjacency-list entries examined is exactly when every vertex is reachable, because each undirected edge appears in two lists.
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 and , and the work grows by exactly the same factor. The farthest cell from a corner is 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 to and uses std::queue. It runs BFS from on the graph of the animation and prints the same visit order, distances and parents.
#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, lists the heads of the edges leaving , and BFS follows edges only forwards. Vertices that cannot be reached from keep : 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.
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, reaches , and but not or ; from only and are reachable. Reachability in a directed graph is not symmetric: reaches , but reaches nothing.
Test yourself
BFS runs from on a connected undirected graph. How many times is each vertex enqueued?
- Once per incident edge
- Exactly once
- At most twice
- Once per level
Why is BFS and not , even though it has a loop over neighbours inside a loop over vertices?
- Because the queue is a linked list
- Because each adjacency list is scanned only once, when its vertex is dequeued, so the inner loop runs times in total
- Because most vertices have degree 1
- Because BFS stops at the first leaf
In the animation's graph, is adjacent to both and . Which becomes its parent, and why?
- , because it is closer to
- , because is dequeued before and discovers first
- Both: gets two parents
- Whichever edge was added last