Sub topic 10
Finding Connected Components
A single BFS from one source reaches only the vertices that source can reach. Many problems ask about the whole graph instead. How many separate networks are there? Which group does each vertex belong to? Is the graph in one piece? Connected components answer these questions. This chapter extends BFS so that it labels every vertex with the component it belongs to.
This chapter assumes you already know the BFS loop from earlier chapters: a deque used as a FIFO queue, and vertices marked visited when they are enqueued. It also assumes you can read O(V + E) complexity arguments. The examples use undirected graphs stored as adjacency lists. A later section covers directed graphs.
What a Connected Component Is
In an undirected graph, two vertices are connected if some path joins them. Connectedness is an equivalence relation:
- Every vertex is connected to itself through the empty path.
- If u connects to v, then v connects to u, because edges go both ways.
- If u connects to v and v connects to w, then u connects to w, because you can join the two paths.
An equivalence relation splits a set into disjoint classes. Here those classes are the connected components. Every vertex belongs to exactly one component. That includes an isolated vertex with no edges, which forms a component of size one.
The Algorithm: An Outer Loop Around BFS
A BFS from a source s visits exactly the vertices that are reachable from s. In an undirected graph, that set is the component containing s. To find every component, loop over all vertices. Whenever a vertex has no label yet, start a new BFS from it and give everything that BFS reaches a fresh component ID.
The component dictionary does two jobs. It is the visited set, and it is the answer.
from collections import deque
def connected_components(graph):
component = {} # vertex -> component id; doubles as the visited set
components = [] # list of member lists, indexed by component id
for source in graph:
if source in component:
continue
cid = len(components)
component[source] = cid
members = [source]
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in component:
component[neighbor] = cid
members.append(neighbor)
queue.append(neighbor)
components.append(members)
return components, component
graph = {
1: [2, 3],
2: [1, 3],
3: [1, 2],
4: [5],
5: [4],
6: [],
}
components, component = connected_components(graph)
print(components) # [[1, 2, 3], [4, 5], [6]]
print(component) # {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2}
print(len(components) == 1) # False: the graph is not connectedHere is how the code runs on this graph. The outer loop reaches vertex 1, finds no label, and starts component 0. That BFS labels 2 and 3. The loop then skips 2 and 3. It starts component 1 at vertex 4, which labels 5. Vertex 6 has no neighbors, so its BFS ends right away and it becomes component 2 by itself.
Why the Total Cost Is Still O(V + E)
Running one BFS per component can look like it costs O(V + E) for each component, which would mean O(k(V + E)) for k components. That bound is too pessimistic. The visited dictionary is shared across all the BFS runs and is never reset, so:
- Each vertex is labeled and enqueued exactly once over the whole run.
- Each vertex is dequeued once, and its adjacency list is scanned once. Summed over all vertices, this scans every adjacency-list entry once. That is E entries for a directed graph and 2E for an undirected one.
- The outer loop adds O(V) work for its checks.
The total is O(V + E) time. The space is O(V) for the labels, plus O(V) at most for the queue.
Building the Graph So No Vertex Goes Missing
Most component bugs come from the graph's input format, not from the BFS loop. Problems often give an edge list and a vertex count. Two mistakes are common:
- Adding each edge in one direction only. If you store an undirected edge (u, v) only as
graph[u].append(v), the BFS from v cannot reach u. One component can then split into several, depending on loop order. - Leaving out isolated vertices. If you create adjacency entries only for vertices that appear in some edge, a vertex with no edges never shows up in the outer loop. Your component count comes out too low.
Create an entry for every vertex first, then add both directions of each edge:
from collections import deque
def build_undirected(vertices, edges):
graph = {v: [] for v in vertices} # every vertex gets an entry, even with no edges
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
return graph
def count_components(graph):
seen = set()
count = 0
for source in graph:
if source in seen:
continue
count += 1
seen.add(source)
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return count
graph = build_undirected(range(7), [(0, 1), (1, 2), (3, 4)])
print(count_components(graph)) # 4: {0, 1, 2}, {3, 4}, {5}, {6}If you used the edge list alone to create the dictionary entries, vertices 5 and 6 would be missing and the function would report 2 components instead of 4.
Directed Graphs: Weak vs. Strong Connectivity
In a directed graph, "connected" splits into two different ideas:
- Weakly connected components treat every edge as undirected. Two vertices are in the same weak component if a path joins them when you ignore edge direction.
- Strongly connected components (SCCs) require a directed path both ways: from u to v and from v to u.
Running the outer-loop BFS directly on a directed adjacency list gives neither one. Take {'A': ['B'], 'B': [], 'C': ['B']}. Starting from A labels A and B as component 0. Then C starts component 1, finds B already labeled, and stops. The result is [['A', 'B'], ['C']].
That answer is wrong for weak components, where all three vertices are in one group. It is also wrong for strong components, where each vertex is alone. The result even depends on loop order: if the loop visited C first, you would get [['C', 'B'], ['A']].
To get weak components, add the reverse of every edge and then run the undirected algorithm. To get strong components, you need a dedicated algorithm such as Kosaraju's or Tarjan's. Kosaraju's algorithm runs two traversals, one on the graph and one on its reverse, and the first pass needs DFS finishing order. That algorithm is beyond this chapter.
Choosing a Method for Components
BFS is one of several ways to find components. The right choice depends on how the graph arrives and whether it changes.
| Method | Time | Strengths | Weaknesses |
|---|---|---|---|
| BFS with outer loop | O(V + E) | Iterative, no recursion limit, gives distances within a component if needed | Needs the full adjacency list up front |
| Recursive DFS with outer loop | O(V + E) | Short code | Python's default recursion limit (about 1000) fails on long paths |
| Union-find (disjoint set union) | Nearly O(V + E α(V)) | Handles edges arriving one at a time, works straight from an edge list | No traversal order or distances; answers "same group?" only |
Use BFS when you have the whole graph and may want more than the labels, such as each component's diameter estimate or distances from a representative vertex. Use union-find when edges are added over time and you need the component count after each addition. BFS would have to rerun from scratch after each new edge.
Edge Cases Worth Testing
- Empty graph: zero vertices gives zero components, and the outer loop never runs.
- Self-loops: an edge (v, v) puts v in its own adjacency list. The visited check ignores it, so it does no harm.
- Parallel edges: duplicate entries cost extra scans but do not change the result.
- Neighbors that are not keys: if some vertex appears only as a neighbor,
graph[node]raisesKeyErrorwhen that vertex is dequeued. Building the graph with an entry for every vertex prevents this. - Grids: counting "islands" in a grid is this same algorithm. The outer loop runs over cells, and the neighbors are adjacent land cells, as in the grid chapter.
Exercise
A graph has 10 vertices and no edges. How many components does connected_components return, how many BFS runs start, and what is the total running time in terms of V and E?
Show answer
It returns 10 components, each a single vertex, and starts 10 BFS runs, one per vertex. Each BFS dequeues one vertex and scans an empty adjacency list. The total is O(V + E) = O(10 + 0), which is linear in V. Many BFS runs do not raise the cost, because each vertex is still handled once.
Exercise
Someone builds an undirected graph from the edges [(0, 1), (2, 1)] but appends each edge only as graph[u].append(v), with entries for vertices 0, 1, and 2. The outer loop visits vertices in the order 0, 1, 2. What does connected_components return, and what is the correct answer?
Show answer
The adjacency list is {0: [1], 1: [], 2: [1]}. The BFS from 0 labels 0 and 1 as component 0. Vertex 1 is skipped. The BFS from 2 finds 1 already labeled, so 2 alone becomes component 1. The function returns [[0, 1], [2]]. The correct answer is a single component, [0, 1, 2], because the edges are undirected.
Exercise
Change connected_components so that it also returns the size of the largest component, without making a second pass over the graph.
Show answer
Keep a variable best = 0 before the outer loop. After each BFS finishes, set best = max(best, len(members)), and return best along with the other results. This adds O(1) work per component, so the total stays O(V + E).