Sub topic 12
Disconnected Graphs and Minimum Spanning Forests
The earlier chapters assumed the input graph is connected, meaning every vertex can reach every other vertex. Real inputs often break that assumption. A road dataset may include islands, and a sensor network may have nodes that are out of range of everyone else. Clustering code may also have removed edges on purpose. This chapter covers what the right answer is for such graphs and how Kruskal's and Prim's algorithms behave on them, including the changes each one needs.
This chapter assumes you have read the chapters on the disjoint-set structure, Kruskal's algorithm, and Prim's algorithm with a binary heap. You should also know what a connected component is: a maximal set of vertices that are all reachable from one another.
What a Minimum Spanning Forest Is
A disconnected graph has no spanning tree. No set of edges can connect two vertices that have no path between them in the original graph. The useful generalization is the minimum spanning forest (MSF). It is a minimum spanning tree for each connected component, taken together.
Three facts follow from that definition:
- If the graph has V vertices and C connected components, every spanning forest has exactly V − C edges. Each component with k vertices needs k − 1 edges, and summing over components gives V − C.
- An isolated vertex has no edges at all. It forms a component of size 1 and contributes zero edges and zero weight.
- The cut and cycle properties still hold inside each component. A cut that separates two different components has no crossing edges, so it never forces a choice. That is why greedy algorithms extend cleanly.
We will use this graph for every example in the chapter. It has V = 7 and C = 3, so the forest must have 7 − 3 = 4 edges.
Kruskal's Algorithm Already Builds a Forest
Kruskal's algorithm never assumed connectivity. It scans edges in sorted order and keeps an edge whenever its endpoints lie in different disjoint sets. On a disconnected graph the disjoint sets simply never all merge. When the edges run out, each remaining set is one component, and the kept edges form the minimum spanning forest.
The version from the Kruskal chapter stops early once it has n - 1 edges. On a disconnected graph that condition never becomes true, so the loop scans every edge. The output is still correct. You only lose the early exit.
The version below drops the early exit. It also reports the component count and the weight of each component's tree, which you get from the disjoint-set roots at no extra cost.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def kruskal_forest(n, edges):
# edges: list of (weight, u, v); vertices numbered 0..n-1
ds = DisjointSet(n)
forest = []
total = 0
for w, u, v in sorted(edges):
if ds.union(u, v):
forest.append((u, v, w))
total += w
components = n - len(forest)
# Weight of each component's tree, keyed by its disjoint-set root.
labels = [ds.find(v) for v in range(n)]
weight_by_root = {r: 0 for r in labels}
for u, v, w in forest:
weight_by_root[ds.find(u)] += w
return total, forest, components, weight_by_root
edges = [(1, 0, 1), (4, 0, 2), (2, 1, 2), (3, 3, 4), (1, 4, 5), (5, 3, 5)]
n = 7 # vertex 6 has no edges
total, forest, components, per_component = kruskal_forest(n, edges)
print(total) # 7
print(forest) # [(0, 1, 1), (4, 5, 1), (1, 2, 2), (3, 4, 3)]
print(components) # 3
print(per_component) # {0: 3, 4: 4, 6: 0}Here is the trace. Sorted, the edges are (1,0,1), (1,4,5), (2,1,2), (3,3,4), (4,0,2), (5,3,5). The first four each join two different sets, so all four are kept. Edge 0–2 is rejected because 0 and 2 are already joined through 1. Edge 3–5 is rejected because 3 and 5 are already joined through 4. Vertex 6 never appears in any edge, so it stays its own root.
The line components = n - len(forest) works because every successful union reduces the number of sets by exactly one. The sets start at n and finish at C, so the number of kept edges is n − C.
Prim's Algorithm Needs a Restart Loop
Prim's algorithm grows one tree from a start vertex. It only ever pushes edges that leave the current tree, so it can never reach a vertex in another component. On our example graph, prim(adj) from the earlier chapter returns weight 3 and covers only vertices 0, 1, and 2. It reports no error, and the result looks plausible.
To get the forest, wrap the single-tree routine in a loop over all vertices. Start a new tree from each vertex that no earlier tree has visited. Each restart finds exactly one component.
import heapq
def prim_forest(adj):
# adj[v] is a list of (neighbor, weight) pairs
n = len(adj)
visited = [False] * n
total = 0
forest = []
components = 0
for s in range(n):
if visited[s]:
continue
components += 1 # s starts a new component
heap = [(0, s, -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), (4, 0, 2), (2, 1, 2), (3, 3, 4), (1, 4, 5), (5, 3, 5)]
n = 7
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, 3), (4, 5, 1)], 3)The trace runs in three rounds. From s = 0 the algorithm adds 0–1 (weight 1), then 1–2 (weight 2), and then discards the stale entry for 2 via 0–2. Vertices 1 and 2 are already visited, so the outer loop skips them. From s = 3 it adds 3–4 (weight 3), then 4–5 (weight 1), and then discards the stale entry for 5 via 3–5. From s = 6 the algorithm pops the starting entry, marks 6 visited, and finds no neighbors.
The edge order differs from Kruskal's output because Prim finishes one component before starting the next. The edge set and the total weight are the same.
The outer loop adds O(V) work, and each vertex and edge is still processed once, so the running time stays O(E log V). Note that the heap is created fresh for each component. Reusing one heap is also correct, because it is always empty when a tree finishes. A fresh heap just makes that fact easier to see.
Comparing the Two Approaches
| Concern | Kruskal | Prim (single start) | Prim with restart loop |
|---|---|---|---|
| Output on disconnected input | Full minimum spanning forest | MST of the start vertex's component only | Full minimum spanning forest |
| Signals disconnection | Kept edges < n − 1 | Visited count < n | Component counter > 1 |
| Isolated vertices | Remain singleton sets | Ignored unless they are the start vertex | Each counted as one component |
| Early exit | Only if C is known | Not applicable | Not applicable |
| Time | O(E log E) | O(E log V) for one component | O(V + E log V) |
Deciding What "Disconnected" Should Mean for Your Caller
A forest is not always the answer you want. Before you write the code, decide how your function should respond to disconnected input:
- Return the forest. This suits clustering and analysis, where components are meaningful.
- Raise an error. This suits network design, where a disconnected result means the plan cannot be built. Check
components > 1after either forest function and raiseValueError. - Return a sentinel, such as infinite total weight. Some competitive-programming problems expect this. It is easy to misuse in production code, because callers may add
infinto other sums without noticing.
Edge Cases and Common Errors
- Inferring n from the edge list. Writing
n = max(max(u, v) for _, u, v in edges) + 1misses isolated vertices with high indices and every vertex when the list is empty. Pass the vertex count explicitly. - Empty graph. With n = 0 both functions return weight 0, no edges, and 0 components. With n ≥ 1 and no edges, they return n components.
- Self-loops. Kruskal rejects them because
union(v, v)returns False. Prim skips them because the vertex is already visited when the entry is popped. Neither one breaks the forest. - Parallel edges. Both algorithms keep the lightest edge between a pair and discard the rest. You do not need to deduplicate first.
- Reporting one total. A single summed weight hides how cost is spread across components. Return per-component weights when callers might need them.
The Super-Vertex Trick
Some libraries only compute spanning trees and reject disconnected input. You can still get a forest from them:
- Add a new vertex X.
- Connect X to every original vertex with weight M, where M is larger than any real edge weight.
- Compute the MST of the augmented graph.
- Drop every edge that touches X.
By the cycle property, the MST uses exactly one X-edge per component. Two X-edges into the same component would form a cycle through X, and an X-edge would be the heaviest edge on it. Removing X therefore leaves the minimum spanning forest, with weight equal to the MST total minus C·M. The trick adds V edges and needs a safe value for M, so use it only when you cannot change the algorithm itself.
Exercises
Exercise
A graph has 10 vertices and 3 connected components, two of which are isolated vertices. How many edges does its minimum spanning forest contain, and how many vertices are in the one non-trivial component?
Show answer
The forest has V − C = 10 − 3 = 7 edges. The two isolated vertices contribute no edges, so the non-trivial component has 8 vertices and 7 edges, which matches 8 − 1.
Exercise
You call the single-start prim(adj) from the Prim chapter on a graph and get total weight 12 with 5 edges, but the graph has 9 vertices. What can you conclude, and what should you do?
Show answer
The tree covers only 6 vertices (5 edges + 1), so the graph is disconnected and 3 vertices were never reached. Weight 12 is the MST of the start vertex's component, not of the graph. Use primforest (or kruskalforest) to get the full forest, or raise an error if the caller requires a connected graph.
Exercise
In kruskal_forest, why does components = n - len(forest) give the right count even when there are isolated vertices?
Show answer
The disjoint-set structure starts with n singleton sets, and each successful union merges two sets into one. After all edges are processed, the number of sets is n minus the number of successful unions, and each successful union added exactly one forest edge. Isolated vertices are never unioned, so they remain singleton sets and are counted correctly.
Exercise
In the super-vertex trick on the example graph from this chapter, choose M = 100. What is the total weight of the augmented MST, and how many edges does it have?
Show answer
The forest weighs 7 and the graph has C = 3 components, so the augmented MST uses three X-edges: 7 + 3 × 100 = 307. The augmented graph has 8 vertices, so its MST has 7 edges: the 4 forest edges plus the 3 X-edges.