Sub topic 10
Finding Connected Components
This chapter assumes you already know the BFS loop from earlier chapters: a deque used as a FIFO queue, a visited set, and marking each vertex as visited at the moment it is enqueued. It also assumes you know that BFS runs in O(V + E) time.
A connected component of an undirected graph is a largest possible set of vertices in which every vertex can reach every other vertex. Every vertex belongs to exactly one component. A vertex with no edges is a component by itself.
The Idea: Restart BFS From Every Unvisited Vertex
A single BFS from a source visits exactly the vertices reachable from that source. In an undirected graph, that set is the source's whole component. To find all components, loop over every vertex. Whenever you reach a vertex that is still unvisited, start a new BFS from it and give every vertex that BFS reaches the same component label.
Implementation
The component dictionary does two jobs. It is the visited set, and it stores each vertex's label.
from collections import deque
def connected_components(graph):
component = {}
count = 0
for source in graph:
if source in component:
continue
component[source] = count
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in component:
component[neighbor] = count
queue.append(neighbor)
count += 1
return count, component
graph = {
1: [2], 2: [1, 3], 3: [2],
4: [5], 5: [4],
6: [],
}
print(connected_components(graph))
# (3, {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2})Once you have the labels, two common questions take constant time each. To check whether u and v are connected, test component[u] == component[v]. The number of components is count.
Complexity Across All the Searches
Running many BFS calls might look like it costs more than O(V + E), but it doesn't. The visited dictionary is shared across all of them, so each vertex is enqueued once in total, not once per search. Each adjacency list is also scanned once in total. The whole procedure is still O(V + E) time and O(V) extra space.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Creating a new visited set inside the outer loop | Vertices get counted again; the count is too high; time grows toward O(V·(V + E)) | Create one visited set or dictionary before the loop |
| Leaving isolated vertices out of the dictionary's keys | Components with a single vertex are never counted | Give every vertex a key, even if its list is empty |
| Storing an undirected edge in only one direction | A component splits in two, depending on where the search starts | Add `v` to `graph[u]` and `u` to `graph[v]` |
| Incrementing `count` inside the inner loop | Labels change partway through a component | Increment only after the queue is empty |
When BFS Is the Right Tool
Labeling components with BFS works well when the graph is fixed and fits in memory. A depth-first search labels components just as well; the visiting order makes no difference to the result. If edges keep arriving and you need to answer "are these connected?" between arrivals, a union-find (disjoint-set) structure is usually the better fit.
Exercise
An undirected graph has vertices 0 to 7 and edges (0,1), (1,2), (3,4), (5,6), (6,7), (7,5). How many connected components does it have, and what are they? If you run connected_components on it with the vertices inserted in order 0 to 7, what label does vertex 7 get?
Show answer
It has three components: {0, 1, 2}, {3, 4}, and {5, 6, 7}. The outer loop starts new searches at 0, 3, and 5, so these components get labels 0, 1, and 2. Vertex 7 gets label 2.
Exercise
A student puts visited = set() inside the for source in graph loop and checks only that local set. Why does this give the wrong count, even though each BFS on its own is correct?
Show answer
Each new BFS forgets which vertices earlier searches labeled. So every vertex starts a new search, and the count comes out as V instead of the number of components. Each component is also explored again from every vertex in it, which wastes time.