Connected components and islands
A connected component is a group of vertices that can all reach each other. Count components by starting a search from every vertex not yet visited, or by joining the two ends of every edge in a disjoint-set structure. A grid of land and water is the same problem with cells as vertices.
How to recognise it
- How many separate groups are there?
- Pairs from different groups, or the size of each group.
- Islands in a grid.
Counting groups
count = 0
for s in vertices:
if s not visited: count += 1; search from s, marking everything reached
Vertices, edges, adjacency lists and the other words used here are on the Structures page.
| Problem | Twist |
|---|---|
| provinces | the graph is an adjacency matrix |
| islands | cells are vertices; neighbours are up, down, left, right |
| journey to the moon | count pairs across groups: add seen × size for each new group |
Common mistakes
- Counting edges instead of starting searches.
- Recursing on huge grids and overflowing the stack; an explicit stack avoids it.
Problems
- Number of Connected Components in an Undirected Graphmediumguide ready
- Number of Provincesmediumguide ready
- Number of Islandsmediumguide ready
- Journey to the Moonmediumguide ready