Learn / Graphs

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.

ProblemTwist
provincesthe graph is an adjacency matrix
islandscells are vertices; neighbours are up, down, left, right
journey to the mooncount 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

0 of 4 solved

Check yourself

Graph on 5 vertices with edges 0-1, 1-2, 3-4. How many components?

Each search from an unvisited vertex finds?

Pairs of astronauts from different countries with sizes 3 and 2: how many?