Number of Islands, visualized step by step

Medium One of the Blind 75 interview problems (LeetCode 200). Technique: breadth-first search on a grid. Solution in Python, explained at every step.

The problem

You get a grid of '1' (land) and '0' (water). An island is a group of land cells joined up, down, left or right; cells that touch only at a corner are not joined. Count the islands.

Example: in the grid with rows 11000, 10011 and 00101 there are 3 islands: three cells in the top-left corner, three on the right, and the single cell in the middle of the bottom row, which touches the right-hand island only at a corner.

The grid with rows 11000, 10011 and 00101. Water cells are light blue; each island is one sand-coloured shape with an outline: three cells in the top-left corner, three on the right, and the single cell in the middle of the bottom row. Answer: 3.
Each outline is one island: land cells joined up, down, left or right.

Note

The cells are the characters '1' and '0', not numbers. A test against the number 1 finds no land, and the count comes out 0.

Try it yourself first: LeetCode 200 ↗. Then step through the solution below.

Brute force

Without marking the land already seen, every land cell would start a search of its own, and an island would be found again from each of its cells. With L land cells that is up to L searches of up to L cells, O(L2), plus a way to tell which results are the same island.

The key insight

The clue is in the words "joined up, down, left or right": a group of joined cells is found by a search from any one of its cells. Scan the grid cell by cell. The first time the scan meets land, that land belongs to an island not counted yet: count it, then visit the whole island from there and mark every one of its cells.

The helper sink does the visiting with breadth-first search: a queue of cells to look at, each one checking its four neighbours and adding the land among them. A cell is marked when it goes into the queue, not when it comes out: otherwise a cell reached from two neighbours would go in twice. Marked cells read as water to the scan, so no island is counted twice.

Note

sink could also be a recursive depth-first search: call it on each land neighbour instead of queueing it. The count is the same, but a large island makes the calls go deep, and in Python an island of about a thousand cells in a row hits the recursion limit. The queue has no such limit.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Number of Islands, step by step

Python

from collections import deque def num_islands(grid):    count = 0    for r in range(len(grid)):        for c in range(len(grid[0])):            if grid[r][c] == '1':                count += 1                sink(grid, r, c)    return count def sink(grid, r, c):    grid[r][c] = '0'    queue = deque([(r, c)])    while queue:        i, j = queue.popleft()        for y, x in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)):            if 0 <= y < len(grid) and 0 <= x < len(grid[0]) and grid[y][x] == '1':                grid[y][x] = '0'                queue.append((y, x))
All steps as text
  1. grid has 3 rows and 5 columns: 1 is land, 0 is water. How many islands are there?
  2. The variable count starts at 0: it counts the islands found.
  3. r and c go through grid row by row. Cell (0, 0) is land, the first of an island.
  4. A new island: count goes up by 1, to 1.
  5. sink turns the whole island into water. It writes 0 into this cell and queues it. The corner number is its island.
  6. Take (0, 0) out of the queue into i, j. The queue holds the cells whose neighbours are still to be looked at.
  7. y, x goes through its four neighbours: the first that is unmarked land is (1, 0).
  8. Write 0 into (1, 0) and put it in the queue.
  9. The next unmarked land neighbour is (0, 1).
  10. Write 0 into (0, 1) and put it in the queue. (0, 0) has no more land neighbours: the next cell comes out of the queue.
  11. Take (1, 0) out of the queue.
  12. None of its four neighbours is unmarked land. The next cell comes out of the queue.
  13. Take (0, 1) out of the queue.
  14. None of its four neighbours is unmarked land. The queue is empty, so island 1 is complete.
  15. The scan passes water and marked cells up to (1, 3): new land.
  16. A new island: count goes up by 1, to 2.
  17. sink turns this island into water too: it writes 0 into the cell and queues it.
  18. Take (1, 3) out of the queue.
  19. Of its four neighbours, the first that is unmarked land is (1, 4).
  20. Write 0 into (1, 4) and put it in the queue. (1, 3) has no more land neighbours: the next cell comes out of the queue.
  21. Take (1, 4) out of the queue.
  22. Of its four neighbours, the first that is unmarked land is (2, 4).
  23. Write 0 into (2, 4) and put it in the queue. (1, 4) has no more land neighbours: the next cell comes out of the queue.
  24. Take (2, 4) out of the queue.
  25. None of its four neighbours is unmarked land. The queue is empty, so island 2 is complete.
  26. The scan reaches (2, 2): land, though it touches the island above only at a corner, and corners do not join.
  27. A new island: count goes up by 1, to 3.
  28. sink turns this island into water too: it writes 0 into the cell and queues it.
  29. Take (2, 2) out of the queue.
  30. None of its four neighbours is unmarked land. The queue is empty, so island 3 is complete.
  31. The scan is over: return 3.
  32. Every cell was scanned once and every land cell went through the queue once: O(rows × cols) time.
Number of Islands, step by step. Last step: Every cell was scanned once and every land cell went through the queue once: O(rows × cols) time.

Note

The code has two functions. num_islands scans the grid row by row and counts the islands. sink turns one island into water, starting from one of its cells, so that the scan never counts it again.

Complexity

ApproachTimeSpace
Brute force: a fresh search from every land cell, each with its own marksO(L2)O(L)
Depth-first search, recursiveO(rows × cols)O(rows × cols)
Union-find over the land cellsO(rows × cols), almostO(rows × cols)
Breadth-first search with a queue this pageO(rows × cols)O(rows × cols)

L is the number of land cells.

  • Time: O(rows × cols). The scan looks at every cell once, and every land cell goes through the queue once and checks four neighbours.
  • Space: O(rows × cols). At worst, for the queue, which never holds more cells than one island has; the marks are written into the grid itself, so nothing else is needed.

Edge cases

  • All water: the scan never finds land, and the count stays 0.
  • All land: the first cell starts one search that marks every cell, so the count is 1.
  • Cells touching only at corners, like 10 over 01: diagonal neighbours are not checked, so these are 2 islands.

Try it: put Number of Islands together step by step

The blocks below are steps of Number of Islands in words, and two of them do not belong. Put the right ones in order and check: your algorithm runs on the example grid, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Number of Islands together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

Can you do it without changing the grid? Keep the visited cells in a set (or a second grid of booleans) instead of overwriting them with '0'. The scan and the search stay the same; the price is O(rows × cols) extra space for the marks.

What if land is added one cell at a time, with the count after each? A new search after every cell costs O(rows × cols) each time. With union-find, a new cell adds one island, and each join with a neighbouring island takes one away: almost O(1) per cell.

The data structure behind it