TExcelTAD
Home › Graph Algorithms › Breadth-First Trees and Printing Paths

Breadth-First Trees and Printing Paths

Breadth-first search leaves behind more than distances. Every discovered vertex remembers its parent v.πv.\pi, 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(G,s)(G, s), define the predecessor subgraph Gπ=(Vπ,Eπ)G_\pi = (V_\pi, E_\pi) by

Vπ={v∈V:v.π≠NIL}∪{s},Eπ={(v.π,v):v∈Vπ∖{s}}V_\pi = \{ v \in V : v.\pi \ne \text{NIL} \} \cup \{ s \}, \qquad E_\pi = \{ (v.\pi, v) : v \in V_\pi \setminus \{ s \} \}

It is a breadth-first tree: VπV_\pi consists of the vertices reachable from ss, and for every v∈Vπv \in V_\pi the subgraph contains exactly one simple path from ss to vv, which is a shortest path in GG.

Proof

BFS sets v.πv.\pi exactly when it discovers vv, and it discovers exactly the reachable vertices, so VπV_\pi is the set of reachable vertices. Every v≠sv \ne s in VπV_\pi has one parent edge, so ∣Eπ∣=∣Vπ∣−1\lvert E_\pi \rvert = \lvert V_\pi \rvert - 1. Following parent pointers from vv strictly decreases dd by one per step (v.d=v.π.d+1v.d = v.\pi.d + 1), so the walk cannot repeat a vertex and must end at ss, the only vertex with d=0d = 0. Hence GπG_\pi is connected, and a connected graph with ∣Vπ∣−1\lvert V_\pi \rvert - 1 edges is a tree. The path from ss to vv in it has v.d=δ(s,v)v.d = \delta(s, v) edges by the BFS theorem, so it is a shortest path.

The tree edges are what the animation highlights as BFS runs. On this 3×33 \times 3 grid, the source AA is a corner:

Printing a path

To print the path from ss to vv, walk the parent pointers back from vv, then print them in the opposite order. A recursive procedure does the reversal for free:

text
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 v

It 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 ss.

python · try it yourself
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 9−1=89 - 1 = 8 edges for the 9 reachable vertices, and the isolated vertex JJ 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 AA to corner II, 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 vv arrives from some uu with u.d=v.d−1u.d = v.d - 1 and an edge (u,v)(u, v), so the number σ(v)\sigma(v) of shortest paths from ss satisfies

σ(s)=1,σ(v)=∑(u,v)∈E,  u.d=v.d−1σ(u)\sigma(s) = 1, \qquad \sigma(v) = \sum_{(u, v) \in E,\; u.d = v.d - 1} \sigma(u)

Processing vertices in BFS order computes it in O(V+E)O(V + E) time, since every uu with smaller dd 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.

python · try it yourself
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 (42)=6\binom{4}{2} = 6 shortest paths from one corner of a 3×33 \times 3 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 II by walking the parent pointers and reversing them.

cpp · try it yourself
#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.

python · try it yourself
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 ss. How many edges does the breadth-first tree have?

  1. 15
  2. 14
  3. 12
  4. 11

How many shortest paths are there between opposite corners of a 3×43 \times 4 grid graph (3 rows, 4 columns of vertices)?

  1. 6
  2. 10
  3. 12
  4. 20

During a BFS of a connected undirected graph, an edge joins two vertices in the same layer. What follows?

  1. The BFS is wrong
  2. The graph contains an odd cycle, so it is not bipartite
  3. The graph is a tree
  4. The edge is a tree edge