Breadth-First Trees and Printing Paths
Breadth-first search leaves behind more than distances. Every discovered vertex remembers its parent , and those pointers form a tree rooted at the source that contains a shortest path to every reachable vertex. This lesson defines that breadth-first tree, proves it is a tree, prints paths from it, and uses the same BFS layers for two more questions: how many shortest paths there are, and whether a graph is bipartite.
The predecessor subgraph
After BFS, define the predecessor subgraph by
It is a breadth-first tree: consists of the vertices reachable from , and for every the subgraph contains exactly one simple path from to , which is a shortest path in .
Proof
BFS sets exactly when it discovers , and it discovers exactly the reachable vertices, so is the set of reachable vertices. Every in has one parent edge, so . Following parent pointers from strictly decreases by one per step (), so the walk cannot repeat a vertex and must end at , the only vertex with . Hence is connected, and a connected graph with edges is a tree. The path from to in it has edges by the BFS theorem, so it is a shortest path.
The tree edges are what the animation highlights as BFS runs. On this grid, the source is a corner:
Printing a path
To print the path from to , walk the parent pointers back from , then print them in the opposite order. A recursive procedure does the reversal for free:
PRINT-PATH(G, s, v)
1 if v == s
2 print s
3 elseif v.pi == NIL
4 print "no path from s to v"
5 else
6 PRINT-PATH(G, s, v.pi)
7 print vIt runs in time linear in the number of vertices on the path, because each call makes at most one recursive call with a vertex one step closer to .
from collections import deque
edges = ["AB", "AD", "BC", "BE", "CF", "DE", "DG", "EF", "EH", "FI", "GH", "HI"]
adj = {v: [] for v in "ABCDEFGHIJ"} # J is an isolated vertex
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, pi = {s: 0}, {s: None}
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if v not in d:
d[v], pi[v] = d[u] + 1, u
q.append(v)
return d, pi
def path(pi, s, v):
if v == s:
return [s]
if v not in pi:
return None
return path(pi, s, pi[v]) + [v]
d, pi = bfs(adj, "A")
print("tree edges:", ", ".join(f"{p}-{v}" for v, p in pi.items() if p))
for v in "EFIJ":
p = path(pi, "A", v)
print(f"path to {v}:", f"{' -> '.join(p)} ({d[v]} edges)" if p else "no path")tree edges: A-B, A-D, B-C, B-E, D-G, C-F, E-H, F-I
path to E: A -> B -> E (2 edges)
path to F: A -> B -> C -> F (3 edges)
path to I: A -> B -> C -> F -> I (4 edges)
path to J: no path
The tree has edges for the 9 reachable vertices, and the isolated vertex is not in it. Each printed path is shortest, but it is only one of the shortest paths: the grid has several routes of length 4 from corner to corner , and alphabetical neighbour order made BFS pick the one along the top row and down the right side.
Counting shortest paths
The BFS layers contain every shortest path, not just the tree's. A shortest path to arrives from some with and an edge , so the number of shortest paths from satisfies
Processing vertices in BFS order computes it in time, since every with smaller is dequeued earlier. This count is the first step of betweenness centrality, which measures how many shortest paths pass through each vertex of a network.
from collections import deque
edges = ["AB", "AD", "BC", "BE", "CF", "DE", "DG", "EF", "EH", "FI", "GH", "HI"]
adj = {v: [] for v in "ABCDEFGHI"}
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
def count_shortest(adj, s):
d, sigma = {s: 0}, {s: 1}
q = deque([s])
while q:
u = q.popleft()
for v in sorted(adj[u]):
if v not in d:
d[v], sigma[v] = d[u] + 1, 0
q.append(v)
if d[v] == d[u] + 1: # u is one layer before v
sigma[v] += sigma[u]
return d, sigma
d, sigma = count_shortest(adj, "A")
for layer in range(max(d.values()) + 1):
print(f"layer {layer}:", ", ".join(f"{v} (sigma {sigma[v]})" for v in d if d[v] == layer))layer 0: A (sigma 1)
layer 1: B (sigma 1), D (sigma 1)
layer 2: C (sigma 1), E (sigma 2), G (sigma 1)
layer 3: F (sigma 3), H (sigma 3)
layer 4: I (sigma 6)
The counts are binomial coefficients, Pascal's triangle laid on the grid: there are shortest paths from one corner of a grid to the other, since each is a choice of which 2 of its 4 steps go down.
In C++
The C++ version computes the tree and the path counts in one BFS and prints the path to by walking the parent pointers and reversing them.
#include <algorithm>
#include <cstdio>
#include <queue>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> edges = {"AB", "AD", "BC", "BE", "CF", "DE", "DG", "EF", "EH", "FI", "GH", "HI"};
const int n = 9;
std::vector<std::vector<int>> adj(n);
for (const auto& e : edges) {
adj[e[0] - 'A'].push_back(e[1] - 'A');
adj[e[1] - 'A'].push_back(e[0] - 'A');
}
for (auto& a : adj) std::sort(a.begin(), a.end());
std::vector<int> d(n, -1), pi(n, -1);
std::vector<long long> sigma(n, 0);
std::queue<int> q;
d[0] = 0; sigma[0] = 1; q.push(0);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) {
if (d[v] == -1) { d[v] = d[u] + 1; pi[v] = u; q.push(v); }
if (d[v] == d[u] + 1) sigma[v] += sigma[u];
}
}
std::string path;
for (int v = 8; v != -1; v = pi[v]) path += static_cast<char>('A' + v);
std::reverse(path.begin(), path.end());
std::printf("tree path to I: %s (%d edges)\n", path.c_str(), d[8]);
for (int v = 0; v < n; ++v) std::printf("%c: d = %d, shortest paths = %lld\n", 'A' + v, d[v], sigma[v]);
}tree path to I: ABCFI (4 edges)
A: d = 0, shortest paths = 1
B: d = 1, shortest paths = 1
C: d = 2, shortest paths = 1
D: d = 1, shortest paths = 1
E: d = 2, shortest paths = 2
F: d = 3, shortest paths = 3
G: d = 2, shortest paths = 1
H: d = 3, shortest paths = 3
I: d = 4, shortest paths = 6
Layers and bipartite graphs
A graph is bipartite if its vertices can be split into two sides with every edge going across (Bipartite Matching in Discrete Mathematics uses such graphs). BFS decides it: colour each vertex by the parity of its layer. By Lemma 1 of the BFS proof, an edge joins two vertices whose layers differ by at most one. Edges between consecutive layers go across. If some edge joins two vertices of the same layer, the two tree paths from their lowest common ancestor plus that edge form a cycle of odd length, and a graph with an odd cycle is never bipartite. So the graph (each component of it) is bipartite exactly when no edge lies inside a layer.
from collections import deque
def bipartite(adj):
side = {}
for s in sorted(adj): # one BFS per component
if s in side:
continue
side[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in sorted(adj[u]):
if v not in side:
side[v] = 1 - side[u]
q.append(v)
elif side[v] == side[u]:
return f"not bipartite: edge {u}-{v} joins two vertices of equal parity"
return "bipartite: " + " | ".join("".join(sorted(v for v in side if side[v] == k)) for k in (0, 1))
def graph(edges):
adj = {}
for u, v in edges:
adj.setdefault(u, []).append(v)
adj.setdefault(v, []).append(u)
return adj
print("3x3 grid: ", bipartite(graph(["AB", "AD", "BC", "BE", "CF", "DE", "DG", "EF", "EH", "FI", "GH", "HI"])))
print("6-cycle: ", bipartite(graph(["AB", "BC", "CD", "DE", "EF", "FA"])))
print("5-cycle + tail:", bipartite(graph(["AB", "BC", "CD", "DE", "EA", "EF"])))3x3 grid: bipartite: ACEGI | BDFH
6-cycle: bipartite: ACE | BDF
5-cycle + tail: not bipartite: edge C-D joins two vertices of equal parity
Test yourself
BFS reaches 12 of a graph's 15 vertices from . How many edges does the breadth-first tree have?
- 15
- 14
- 12
- 11
How many shortest paths are there between opposite corners of a grid graph (3 rows, 4 columns of vertices)?
- 6
- 10
- 12
- 20
During a BFS of a connected undirected graph, an edge joins two vertices in the same layer. What follows?
- The BFS is wrong
- The graph contains an odd cycle, so it is not bipartite
- The graph is a tree
- The edge is a tree edge