1def islands(land):2 todo, parts = set(land), []3 for s in land:4 if s not in todo: continue5 todo.remove(s)6 part, q = [s], deque([s])7 while q:8 for n in near(q.popleft()):9 if n in todo:10 todo.remove(n)11 part.append(n)12 q.append(n)13 parts.append(part)14 return partsq[0]q[1]q[2]len(parts)11111111212131312131
Raised squares: land (nodes); low squares: waterFlat traces: edges between land squares that share a sideNumbered chips: the island each square was flooded intoLand squares are nodes and shared sides are edges. The cursor scans land in reading order; each square still in todo starts a breadth-first flood that drops a numbered chip on every square of its island. Three floods, three connected components. With diagonal neighbours the two corner links join them into one.

A grid is a graph

  1. Each square of this 4 × 5 map is land or water. Make every land square a node, and join two land squares with an edge when they share a side: up, down, left or right. That gives 10 nodes and 8 edges.

Flood fill

Cost and neighbours

What happens

;; step 1/8 · grid-graph
  row 0  # # . . .
  row 1  # # . # #
  row 2  . . # . #
  row 3  . # # . .

# = land (10 nodes), . = water
edges (shared sides): 8
  (0, 0) – (0, 1)
  (0, 0) – (1, 0)
  (0, 1) – (1, 1)
  (1, 0) – (1, 1)
  (1, 3) – (1, 4)
  (1, 4) – (2, 4)
  (2, 2) – (3, 2)
  (3, 1) – (3, 2)
a square is (row, column), counted from 0

This is what MIT 6.006 calls Full-BFS: run a search from any unvisited node, put everything it reaches in one component, repeat until no node is left. It runs in O(|V| + |E|) time. Sedgewick and Wayne's CC.java does the same with depth-first search. near() returns squares off the map, such as (-1, 0). They are never in todo, so the code needs no bounds check.