Sub topic 12
Disconnected Graphs and Minimum Spanning Forests
This chapter assumes you have read the earlier chapters on Kruskal's algorithm (with its DisjointSet and kruskal functions) and Prim's algorithm (with its lazy prim function). You should also be comfortable with the idea of a connected component.
Why a disconnected graph has no spanning tree
A spanning tree must reach every vertex. If the graph splits into separate pieces with no edges between them, no set of edges can connect those pieces, so a spanning tree does not exist. Real inputs often look like this. A road dataset can contain islands, and a sensor network can have nodes that are out of range.
The useful generalization is the minimum spanning forest (MSF). It is the set of MSTs, one per connected component. If a graph has V vertices and c components, every spanning forest has exactly V − c edges. Each component with k vertices contributes a tree with k − 1 edges.
Kruskal already builds a forest
Kruskal's algorithm never assumes the graph is connected. It processes edges in sorted order and keeps any edge that joins two different sets. On a disconnected graph it simply never finds an edge that joins two components, so it finishes holding one tree per component.
The early break when len(mst) == n - 1 never fires on a disconnected graph. The loop runs through every edge, which is still O(E log E). That gives you a free connectivity check:
# Uses DisjointSet and kruskal from the Kruskal chapter.
edges = [(1, 0, 1), (3, 0, 2), (2, 1, 2), (4, 3, 4)]
n = 5
total, forest = kruskal(n, edges)
components = n - len(forest)
print(total, forest, components) # 7 [(0, 1, 1), (1, 2, 2), (3, 4, 4)] 2If components > 1, the input was disconnected and the result is a forest, not a tree.
Prim needs a restart loop
Prim's algorithm grows one tree outward from a start vertex. When its heap empties, it has covered only the start vertex's component. The prim function from the earlier chapter returns a result without any error, which makes this a common silent bug: the total weight looks plausible, but some vertices are missing.
The fix is to run Prim again from each vertex that is still unvisited. Every restart begins a new component:
import heapq
def prim_forest(adj):
# adj: list where adj[v] is a list of (neighbor, weight) pairs
n = len(adj)
visited = [False] * n
total = 0
forest = []
components = 0
for root in range(n):
if visited[root]:
continue
components += 1
heap = [(0, root, -1)]
while heap:
w, v, parent = heapq.heappop(heap)
if visited[v]:
continue
visited[v] = True
total += w
if parent != -1:
forest.append((parent, v, w))
for u, wu in adj[v]:
if not visited[u]:
heapq.heappush(heap, (wu, u, v))
return total, forest, components
edges = [(1, 0, 1), (3, 0, 2), (2, 1, 2), (4, 3, 4)]
n = 5
adj = [[] for _ in range(n)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
print(prim_forest(adj)) # (7, [(0, 1, 1), (1, 2, 2), (3, 4, 4)], 2)The outer loop visits each vertex once and each edge is pushed at most twice, so the running time stays O(E log V). A vertex with no edges counts as its own component and contributes no edges.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling single-start `prim` on a disconnected graph | Missing vertices, total too low | Restart from every unvisited vertex |
| Assuming `kruskal` returned V − 1 edges | Code downstream treats a forest as a tree | Compare `len(forest)` with `n - 1` |
| Forgetting isolated vertices | Component count off by the number of isolated vertices | Number vertices 0..n−1 and pass `n` explicitly |
| Building `adj` from edges only | Isolated vertices missing from `adj` | Allocate `adj` with `n` empty lists first |
Exercise
A graph has 9 vertices and 3 connected components, one of which is a single isolated vertex. How many edges does its minimum spanning forest contain, and how many times does the outer loop of prim_forest start a new tree?
Show answer
The forest has V − c = 9 − 3 = 6 edges. The outer loop starts a new tree 3 times, once per component, including the isolated vertex, which adds no edges.
Exercise
Why does Kruskal's early break never trigger on a disconnected graph, and does this change its asymptotic running time?
Show answer
The forest can hold at most V − c edges, which is fewer than V − 1 when c > 1, so the length check never succeeds and every edge gets processed. The time is still O(E log E), because sorting dominates and the union-find work across all edges is nearly linear.