0:00 / 0:00

Count the islands in a grid of land and water. Scan for land, and sink each island you find so it's only counted once.

▼

The problem

Given a grid of '1' (land) and '0' (water), count the islands: groups of land tiles joined up, down, left or right (diagonals don't join).

Example (5 rows × 7 columns) → 4 islands of 5, 4, 1 and 3 tiles (13 land tiles, 78 pairs of land tiles):

1 1 0 0 0 1 1
1 1 1 0 0 0 1
0 0 0 1 0 0 1
0 1 1 0 0 0 0
0 1 0 0 0 0 0
TRY IT ON LEETCODE ▶

The solution

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])
    def sink(r, c):
        if r < 0 or r >= rows or c < 0 or c >= cols:
            return                     # edge
        if grid[r][c] != '1':
            return                     # water
        grid[r][c] = '0'               # sink it
        for dr, dc in (1,0), (-1,0), (0,1), (0,-1):
            sink(r + dr, c + dc)
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1':
                count += 1             # new island
                sink(r, c)
    return count

Transcript

Number of Islands. You get a map drawn as a grid: ones are land, and zeros are water. Count the islands: land joined up, down, left or right. Touching at a corner doesn't count.

This map has five rows and seven columns, and four islands: a big one, a hook, a single tile, and a small one at the bottom. The single tile meets the others only at its corners, so it stands alone.

Counting land tiles gives thirteen, not four. You could check every pair of land tiles for a path between them: seventy-eight pairs, each one its own search. It works, but it's slow.

The trick: sink each island the moment you find it. Scan the map tile by tile. Water? Move on. Land? That's a new island: add one. Then flood it, turning every land tile joined to it into water. The island is gone, so it's never counted again.

In code, a helper called sink stops if it's off the map or on water. Otherwise, it turns the tile to water and calls itself on all four neighbors. That's depth first search; a queue, breadth first, works too. The main loop visits every tile, and on land, it adds one and sinks.

Let's run it. The scan starts top left: land! Island one, and the flood sinks five tiles. Along the top row, more water, then land: island two, the hook, four tiles. The next row is water, or already sunk. Then the single tile: island three. At the bottom, island four, three tiles. The rest is water. Four islands.

Every tile is scanned once and sunk at most once, so the time is rows times columns. In the worst case, one huge island, the recursion goes that deep too, so the space is rows times columns.

Find land, count it, sink it. That's Number of Islands.