Connected components and grid flood fill
About this lesson
How many islands are on this map? Treat the map as a graph, with land squares as nodes and shared sides as edges, and the question becomes: how many connected components does the graph have? Scan the land in reading order, and start a breadth-first flood from every square no earlier flood reached. Each flood collects exactly one component. The Software lessons "Graphs" and "Graph search: BFS and DFS" cover the search itself, and the Maths lesson "Graph theory: vertices, edges and breadth-first search" defines paths and connectivity.
A map is a graph
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.
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
Read the lesson step by step
A map is a graph
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.
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 0Scan for unseen land
A connected component is a biggest group of nodes joined by paths. To find them all, the code walks the land squares in reading order. todo holds every square not yet in an island; a square still in todo starts a new one.
land, in reading order: (0, 0) (0, 1) (1, 0) (1, 1) (1, 3) (1, 4) (2, 2) (2, 4) (3, 1) (3, 2) todo = set(land) every square, none labelled yet parts = [] one list per island found line 4: skip a square that left todo alreadyFlood the first island
(0, 0) is in todo, so it starts a part. Breadth-first search spreads from it: pop a square from the queue; each neighbour still in todo is removed, added to the part and queued. 4 squares: island 1.
part 1: scan (0, 0): in todo → part 1, q = [(0, 0)] pop (0, 0) add (1, 0), q = [(1, 0)] add (0, 1), q = [(1, 0), (0, 1)] pop (1, 0) add (1, 1), q = [(0, 1), (1, 1)] pop (0, 1) pop (1, 1) parts.append(part) → len(parts) = 1 island 1 = (0, 0) (1, 0) (0, 1) (1, 1)Skip, then flood again
The scan moves on. (0, 1), (1, 0) and (1, 1) left todo during the flood, so line 4 skips them. (1, 3) is new: flood it. The queue reaches (1, 4), then (2, 4). Island 2 has 3 squares.
part 2: scan (0, 1): not in todo, skip scan (1, 0): not in todo, skip scan (1, 1): not in todo, skip scan (1, 3): in todo → part 2, q = [(1, 3)] pop (1, 3) add (1, 4), q = [(1, 4)] pop (1, 4) add (2, 4), q = [(2, 4)] pop (2, 4) parts.append(part) → len(parts) = 2 island 2 = (1, 3) (1, 4) (2, 4)Corners do not connect
(1, 4) is skipped. (2, 2) touches island 1 only at a corner, and a corner is not an edge, so no flood reached it. It starts island 3: (2, 2), then (3, 2), then (3, 1).
part 3: scan (1, 4): not in todo, skip scan (2, 2): in todo → part 3, q = [(2, 2)] pop (2, 2) add (3, 2), q = [(3, 2)] pop (3, 2) add (3, 1), q = [(3, 1)] pop (3, 1) parts.append(part) → len(parts) = 3 island 3 = (2, 2) (3, 2) (3, 1)3 connected components
The scan skips the last three squares, all filled already. parts now holds 3 lists, one per island, so len(parts) is 3. Every land square sits in exactly one part: 4 + 3 + 3 = 10.
end of the scan: scan (2, 4): not in todo, skip scan (3, 1): not in todo, skip scan (3, 2): not in todo, skip return parts: 1: (0, 0) (1, 0) (0, 1) (1, 1) 2: (1, 3) (1, 4) (2, 4) 3: (2, 2) (3, 2) (3, 1) len(parts) = 3Each square once
Each land square leaves todo once, so it is queued once and popped once, checking 4 neighbours: here 10 pops and 40 checks. That is O(V + E) for any graph, and O(R × C) for a whole grid of R rows and C columns.
pops: 10 (one per land square) checks: 40 (4 per pop) adds: 7 (+ 3 starts = 10) set: x in s, s.remove(x) O(1) average deque: append, popleft O(1) total: O(V + E); a grid has E ≤ 2V building land from the grid: O(R × C)Diagonals change the answer
Whether corners count is part of the problem. With 8 neighbours, diagonals are edges too: (1, 1)–(2, 2) and (2, 2)–(1, 3) link all three islands, and the count drops to 1. Only near() would change.
8 neighbours: add (r±1, c±1) to near() (1, 1) – (2, 2) joins two islands (2, 2) – (1, 3) joins two islands 4 neighbours: 3 islands 8 neighbours: 1 island of 10 squares
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01On the lesson's map, why are (1, 1) and (2, 2) in different islands?
near() returns only up, down, left and right. (2, 2) is diagonal to (1, 1), so the flood from (0, 0) never reaches it, and the scan later starts island 3 there.
02In islands(), what does line 4 (if s not in todo: continue) do?
land holds only land squares. A square leaves todo the moment a flood adds it, so a square missing from todo already belongs to an island and must not start a new one.
03A map has V land squares and E edges between them. How long does islands() take?
Each land square leaves todo once, so it is queued and popped once, and each pop checks its neighbours: O(V + E) with O(1) average set operations. On a grid E ≤ 2V, so this is also O(V).
04If near() also returned the four diagonal squares, how many islands would the lesson's map have?
The diagonal links (1, 1)–(2, 2) and (2, 2)–(1, 3) join island 1 to island 3 and island 3 to island 2, so all 10 land squares form one component.
05Why does the code use collections.deque and popleft() instead of a list and pop(0)?
The Python docs give deque O(1) appends and pops at either end. Removing the first item of a list shifts the rest, which would make each pop O(n).
Glossary
- Connected component
- A largest group of nodes in an undirected graph where every node can reach every other along edges.
- Flood fill
- Starting from one square and spreading to every connected square of the same kind, usually with BFS or DFS.
- 4-neighbours
- The squares that share a side with a square: up, down, left and right. With 8-neighbours the four diagonals count too.
- Full-BFS
- Running BFS again from every node not yet visited, until all nodes are visited. Each run finds one component.
- todo set
- Here, the land squares not yet put in any island. A square leaves it the moment a flood reaches it.
- Queue
- A first-in, first-out line. BFS takes squares from the front and adds new ones at the back.
- O(V + E)
- Time proportional to the number of nodes plus the number of edges: every node and edge is handled a constant number of times.
Notes and sources
- 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.
- Depth-first search works just as well: any search that reaches every node it can from the start square finds the same islands. Only the order inside each part changes.
- A recursive depth-first flood fill can go one call deep per square. Python caps the stack depth (sys.getrecursionlimit), so on a large grid the recursive version can raise RecursionError. The queue version here has no such limit.
- near() returns squares off the map, such as (-1, 0). They are never in todo, so the code needs no bounds check.
- The O(1) costs are averages: set lookups and removals are O(1) on average and O(n) in the worst case, and deque append and popleft are O(1). Popping from the front of a list would cost O(n) each time.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 10: Depth-First Search (Full-BFS, Full-DFS, connected components)
- Sedgewick and Wayne, Algorithms 4th ed., §4.1 Undirected Graphs (connected components, CC.java)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 20: Elementary Graph Algorithms
- Python documentation: collections.deque
- Python documentation: Time complexity of built-in types
- Python documentation: sys.setrecursionlimit
Quiz Unlocks after the last step.