Data structures problem 24 of 30

Count the islands

  • Data structures
  • Medium

A grid of "1" (land) and "0" (water) is given as a list of strings. An island is a group of land cells connected up, down, left or right. Write count_islands(grid).

grid = [
    "11000",
    "11000",
    "00100",
    "00011",
]
count_islands(grid)   # 3
Show hint

Scan every cell. When you find land you have not visited, that is a new island: count it, then visit all the land connected to it so you do not count it again.

Show solution
def count_islands(grid):
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    seen = set()
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1" or (r, c) in seen:
                continue
            islands += 1
            stack = [(r, c)]
            seen.add((r, c))
            while stack:
                y, x = stack.pop()
                for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                    if 0 <= ny < rows and 0 <= nx < cols:
                        if grid[ny][nx] == "1" and (ny, nx) not in seen:
                            seen.add((ny, nx))
                            stack.append((ny, nx))
    return islands

The grid is really a graph: each land cell is a node joined to its land neighbours, and islands are connected components. The explicit stack does a depth-first search without recursion, so a huge island cannot hit Python's recursion limit. Each cell is handled a constant number of times: O(rows × cols).

Want a problem like this every day? See today's problem and keep a streak going.