Python coding

Count the islands

A map is a list of equal-length strings where "1" is land and "0" is water. An island is a group of land cells joined up, down, left or right (diagonals don't connect). Return how many islands the map has.

The map may be empty.

  • count_islands(["11110","11010","11000","00000"]) → 1
  • count_islands(["11000","11000","00100","00011"]) → 3
  • count_islands(["101","010","101"]) → 5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Treat the map as a graph: each land cell is a node, and its neighbors are the adjacent land cells in 4 directions.

Hint 2

Scan every cell. An unvisited land cell is a new island: count it, then flood everything reachable from it with an explicit stack, marking cells visited when you push them.

Solution and why it works
pythonO(R·C), R × C = grid size · O(R·C)
def count_islands(grid: list[str]) -> int:
    rows, cols = len(grid), len(grid[0]) if grid else 0
    seen, count = set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1" or (r, c) in seen:
                continue
            count += 1
            seen.add((r, c))
            stack = [(r, c)]
            while stack:
                i, j = stack.pop()
                for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                    inside = 0 <= ni < rows and 0 <= nj < cols
                    if inside and grid[ni][nj] == "1" and (ni, nj) not in seen:
                        seen.add((ni, nj))
                        stack.append((ni, nj))
    return count

Counting islands is counting connected components: each unvisited land cell starts a traversal that marks its whole island, so no island is counted twice. Every cell is pushed at most once and checks 4 neighbors, so the work is linear in the cells. Mark visited on push, not on pop, and prefer an explicit stack: a recursive DFS on a long, snake-shaped island can pass Python's default 1,000-frame recursion limit.