Sub topic 12
Finding Connected Components
This chapter assumes you can write recursive DFS over an adjacency-list dictionary. It also assumes you know how the outer loop of a full-graph traversal builds a DFS forest, and that you are comfortable with Python sets and dictionaries. Here we use that forest to answer a common question about a graph: which vertices can reach each other?
What a Connected Component Is
In an undirected graph, a connected component is a largest set of vertices in which every pair is joined by some path. "Largest" means you cannot add another vertex and keep the property. Every vertex belongs to exactly one component. An isolated vertex with no edges forms a component of size one.
Components split the vertex set into disjoint groups. This lets you answer many questions with a single label lookup:
- Can vertex
ureach vertexv? Only if they share a component. - How many separate networks, friend groups, or circuit regions exist?
- Which pieces must be connected to make the whole graph connected? You need at least
k - 1new edges forkcomponents.
Why DFS Finds Components
A DFS started at vertex s visits every vertex reachable from s and nothing else. In an undirected graph, "reachable from s" is exactly the component containing s. So each tree in the DFS forest covers exactly one connected component.
The algorithm follows from that:
- Loop over every vertex.
- If the vertex has no label yet, start a new DFS from it and give the current component number to everything that DFS reaches.
- Increase the component number.
The number of DFS launches from the outer loop equals the number of components.
Building the Graph Correctly
Most bugs in component counting come from how the graph is built, not from the traversal. Graphs often arrive as a vertex list plus an edge list. For an undirected graph, you must add each edge in both directions. You must also create an entry for every vertex, including ones with no edges.
def build_undirected(vertices, edges):
graph = {v: [] for v in vertices}
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
return graph
graph = build_undirected([1, 2, 3, 4, 5, 6], [(1, 2), (2, 3), (4, 5)])
print(graph)
# {1: [2], 2: [1, 3], 3: [2], 4: [5], 5: [4], 6: []}If you built the dictionary only from the edge list, vertex 6 would never appear and your count would be 2 instead of 3.
Labeling Components Recursively
The version below stores a component number for each vertex. It does not use a separate visited set. A vertex counts as visited once it has a label, so the component dictionary does both jobs.
def connected_components(graph):
component = {}
count = 0
def visit(node, label):
component[node] = label
for neighbor in graph[node]:
if neighbor not in component:
visit(neighbor, label)
for node in graph:
if node not in component:
visit(node, count)
count += 1
return count, component
graph = {1: [2], 2: [1, 3], 3: [2], 4: [5], 5: [4], 6: []}
count, component = connected_components(graph)
print(count) # 3
print(component) # {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2}
def same_component(component, u, v):
return component[u] == component[v]
print(same_component(component, 1, 3)) # True
print(same_component(component, 3, 4)) # FalseAfter one O(V + E) pass, each reachability query becomes an O(1) dictionary lookup. That is a big improvement over running a fresh search for every query.
An Iterative Version That Returns the Groups
Sometimes you want the members of each component rather than a label per vertex. The iterative version below also avoids Python's recursion limit, which is about 1000 frames by default. A recursive DFS on a long path of 10,000 vertices would crash with RecursionError.
def components_iterative(graph):
seen = set()
groups = []
for start in graph:
if start in seen:
continue
seen.add(start)
stack = [start]
group = []
while stack:
node = stack.pop()
group.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
groups.append(group)
return groups
graph = {1: [2], 2: [1, 3], 3: [2], 4: [5], 5: [4], 6: []}
print(components_iterative(graph)) # [[1, 2, 3], [4, 5], [6]]Complexity
The outer loop touches each vertex once. Each launched DFS processes every vertex in its component once and scans each of their adjacency lists once. Summed across all components, that is every vertex and every list entry exactly once:
| Resource | Cost | Reason |
|---|---|---|
| Time | O(V + E) | Each vertex is labeled once and each adjacency entry (2E in an undirected graph) is scanned once |
| Extra space | O(V) | The label dictionary plus a recursion or explicit stack that can hold up to V vertices |
The outer loop does not add a multiplicative factor. Later loop iterations find already-labeled vertices and skip them in O(1) time.
Edge Cases and Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Edges added in one direction only | Too many components. For example, with edge `(2, 1)` stored only as `2 -> 1`, a DFS from 1 never reaches 2 | Append both `u -> v` and `v -> u` |
| Isolated vertices missing from the dictionary | Too few components | Initialize an entry for every vertex first |
| Incrementing the count inside `visit` | Count equals the number of vertices | Increment only in the outer loop, after a launch |
| Deep recursion on large sparse graphs | `RecursionError` | Use the explicit-stack version |
| Self-loops or duplicate edges | No error, slightly more work | Nothing needed, because the label check skips them |
Directed graphs
In a directed graph, "connected" is ambiguous. If you ignore edge direction, which in practice means building the adjacency list with both directions, the method above finds weakly connected components. These are vertices linked by some path when arrows are ignored. Running the directed graph's own adjacency lists through the code above gives wrong answers. The result then depends on vertex order, because a DFS from a in a -> b reaches b but a DFS from b does not reach a. Groups where every vertex can reach every other along the arrows are strongly connected components, and they need the extra machinery covered in a later chapter.
DFS Versus Union-Find
Union-find, also called disjoint-set union, is a data structure that merges sets and tells you which set an element belongs to. It also computes components. The better choice depends on how the graph arrives:
| Situation | Better choice | Reason |
|---|---|---|
| Whole graph known up front, static | DFS | Simple, linear time, no extra structure |
| Edges arrive one at a time, with queries in between | Union-find | Each union or find runs in nearly constant amortized time, with no re-traversal |
| You need traversal facts as well (paths, depths, cycles) | DFS | Union-find only tracks set membership |
| Edges are deleted | Neither directly | Needs dynamic connectivity techniques or a recompute |
Breadth-first search would also find the same components. Any complete traversal works. DFS is the usual choice because it is short to write and fits with the other DFS techniques in this tutorial.
Exercises
Exercise
A graph has 10 vertices and no edges. What do connected_components return for the count, and how many DFS launches happen?
Show answer
The count is 10. Each vertex is its own component, so the outer loop launches 10 separate DFS calls, each of which labels a single vertex and finds an empty adjacency list.
Exercise
Someone builds an undirected graph from the edges (1, 2), (3, 2) by adding only u -> v, giving {1: [2], 2: [], 3: [2]}. What does connected_components report, and why is it wrong?
Show answer
It reports 2 components with labels {1: 0, 2: 0, 3: 1}. The DFS from 1 reaches 2, but 2 has no edge back toward 3, so vertex 3 later starts its own component. The real graph is one component, because 1-2-3 form a path. Adding each edge in both directions fixes it.
Exercise
You add one new edge to an undirected graph that has k components. What are the possible new component counts?
Show answer
Either k or k - 1. If both endpoints are already in the same component, nothing merges and the count stays k. If they are in different components, those two merge and the count drops to k - 1. One edge can never merge more than two components.
Exercise
Modify connected_components so it also returns the size of the largest component, without making a second pass over the graph.
Show answer
Keep a sizes list. Append 0 before each launch from the outer loop and increment sizes[label] inside visit each time a vertex is labeled. After the loop, return max(sizes) if sizes is non-empty, otherwise 0. The sizes for the example graph are [3, 2, 1], so the answer is 3.