Sub topic 12
Finding Connected Components
This chapter assumes you can write recursive DFS over an adjacency-list dictionary. It also assumes you know the outer loop from the DFS forest chapter, which starts a new search from every vertex that has not been visited yet. Everything here applies to undirected graphs. Directed graphs need a different notion, which a later chapter covers.
What a component is
A connected component is a largest set of vertices in which every vertex can reach every other vertex. "Largest" means you cannot add another vertex and keep that property. Every vertex belongs to exactly one component, and a vertex with no edges forms a component by itself.
Components answer questions like these: Which users belong to the same friend cluster? Does this network have parts that cannot reach each other? How many separate pieces does this mesh have?
The working model
One DFS call that starts at vertex s visits exactly the vertices reachable from s, which is s's whole component. The outer loop starts a new DFS only from a vertex that no earlier search reached. So each launch from the outer loop finds exactly one new component, and the number of launches equals the number of components.
Instead of a plain visited set, store a component ID for each vertex. The dictionary still works as the visited check, and it also records which component each vertex belongs to.
def connected_components(graph):
component = {} # vertex -> component id; doubles as the visited set
count = 0
def visit(node, cid):
component[node] = cid
for neighbor in graph[node]:
if neighbor not in component:
visit(neighbor, cid)
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, labels = connected_components(graph)
print(count) # 3
print(labels) # {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2}With the labels stored, "are u and v connected?" becomes a constant-time lookup: labels[u] == labels[v]. The whole labeling pass runs in O(V + E), because every vertex is labeled once and every adjacency list is scanned once.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Storing each undirected edge in only one direction | One component is reported as several, depending on which vertex the loop reaches first | Add every edge `u-v` to both `graph[u]` and `graph[v]` |
| Leaving isolated vertices out of the dictionary | The count is too low, or a lookup raises `KeyError` | Give every vertex a key, even if its list is empty |
| Running this code on a directed graph | Counts depend on vertex order and mean nothing | Use weak connectivity (ignore edge direction) or strongly connected components |
| Recursing on a very large component | `RecursionError` once the depth passes about 1000 | Use the explicit-stack DFS from the earlier chapter |
Building the adjacency list correctly
Most component bugs come from building the graph, not from the search itself. When you build the graph from an edge list, add each edge in both directions:
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
g = build_undirected(range(1, 7), [(1, 2), (2, 3), (4, 5)])
print(connected_components(g)[0]) # 3Run this block in the same file as connected_components.
Exercise
Someone runs connected_components on {"a": ["b"], "b": [], "c": ["b"]}, intending the edges as undirected. What count is returned, what is the correct count, and why do they differ?
Show answer
The function returns 2. The DFS from "a" labels a and b. When the loop reaches "c", c is unlabeled, so it starts a new component, and its neighbor b is already labeled and gets skipped. The correct count is 1, because a-b and b-c join all three vertices. The edges were stored in one direction only, so b's list never points back to a or c. Adding the reverse edges fixes it.
Exercise
How would you change connected_components to return a list of components, each a list of vertices, instead of a label dictionary?
Show answer
Before each launch from the outer loop, append an empty list to a result list. Inside visit, append the node to the last list, result[-1]. You can still use a set or the label dictionary to track visited vertices.