Connected components
Group the nodes of an undirected graph by whether they can reach each other: each unlabelled node starts a new search.
In an undirected graph, a connected component is a largest group of nodes that can all reach each other. To find every component:
Read the full explanation ↓- Time:
O(V + E) - Space:
O(V) - Horowitz–Sahni, chapter 6
- CLRS, chapter 19
Three components: a triangle, a three-node chain and a pair.
def components(graph, src):comp = {v: 0 for v in graph}count = 0for s in graph:if comp[s] == 0:count = count + 1comp[s] = countstack = [s]while stack:u = stack.pop()for v, _ in graph[u]:if comp[v] == 0:comp[v] = countstack.append(v)return comp
Start
- Current node
(u) - Search tree (from parent)
- Edge being checked
Stack stack
empty
Local variables
src'A'
Orange = changed in this step
graph dict
- 'A': [('B', 1), ('C', 1)]
- 'B': [('A', 1), ('C', 1)]
- 'C': [('B', 1), ('A', 1)]
- 'D': [('E', 1)]
- 'E': [('D', 1), ('F', 1)]
- 'F': [('E', 1)]
- 'G': [('H', 1)]
- 'H': [('G', 1)]
Call stack
- components()line 1
Step 1 of 91
How the work grows with input size
Average of 5 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- check
- visit
- current input (n=8)
Show as a table
| n | check | visit |
|---|---|---|
| 4 | 10.4 | 4 |
| 8 | 27.6 | 8 |
| 12 | 41.6 | 12 |
| 16 | 56 | 16 |
| 20 | 70.8 | 20 |
| 24 | 74.4 | 24 |
| 28 | 94.4 | 28 |
Explanation
The idea
In an undirected graph, a connected component is a largest group of nodes that can all reach each other. To find every component:
- Go through the nodes in order.
- If a node has no label yet, increase the component counter and start a search from it (here a DFS with a stack); every node the search reaches gets the same label.
Cost
Every node is labelled once and every edge is checked at most twice: O(V + E).
What to watch in the trace
- The number next to each node is its component number (0 means not labelled yet).
- The stack is under the picture; use the "every loop round" detail level to see only the start of each new component.