Algorithms · Graphs & grids

Number of Islands

How many separate islands are on the map?

The problem

The map has land (1) and water (0). Land squares touching up, down, left or right belong to the same island. Return how many islands there are. (LeetCode writes the squares as text, "1" and "0".)

islands([[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])3
islands([[1, 1, 1], [0, 1, 0], [1, 1, 1]])1
Graphs & grids. Spread out in rings. Drop a stone in a pond: the ripple reaches everything one step away, then two steps…

Now ask: what if there were a billion?

Same question on a social network: “how many separate friend groups are there?” is counting islands on a graph of billions of people. Google’s PageRank works on a graph like that: the whole web.

Aim for O(n)🧩 classic

Think it through

You find a land square. When is it a new island?

  • Always
  • Only if it isn’t part of an island you already counted
Show the answer

Only if it isn’t part of an island you already counted. Counting every square would count each island many times. The trick is to never meet a counted island again.

How do you make sure you never count it again?

  • Keep a list of counted squares and search it
  • Sink the whole island (turn it to water) when you find it
Show the answer

Sink the whole island (turn it to water) when you find it. Spread out from the square and turn all of its land to water. Each square is sunk once, so the whole map takes one pass.

Stuck? 3 nudges, smallest first
  1. When you find land, it’s a new island only if you haven’t already counted it as part of another one.
  2. So when you find new land, sink the whole island (turn it to 0) by spreading out from it. Then it can’t be counted again.
  3. On new land: count += 1, set it to 0, and run a queue that sinks every connected land square.

The fast way

Try it yourself before you open this.

Show the fast version
from collections import dequea queue that's quick at both ends
def islands(grid):take a map of 1s (land) and 0s (water)
count = 0islands found so far
for r in range(len(grid)):each row
for c in range(len(grid[0])):each square in the row
if grid[r][c] == 1:new land we haven't sunk yet
count += 1a new island!
grid[r][c] = 0sink this square
queue = deque([(r, c)])then spread out from it
while queue:while the ripple spreads
y, x = queue.popleft()the next square
for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):its four neighbours
if 0 <= ny < len(grid) and 0 <= nx < len(grid[0]) and grid[ny][nx] == 1:land?
grid[ny][nx] = 0sink it (so it's never counted again)
queue.append((ny, nx))and spread from it later
return counthow many

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with graphs & grids