~/problems / Graphs / DFS and connected components

Number of Islands

easy ~15 min

Implement num_islands(grid) -> int.

grid is a list of rows, each a list of the characters "1" (land) and "0" (water). An island is a group of land cells joined horizontally or vertically (diagonals don't count). Everything outside the grid is water. Return how many islands there are.

num_islands([
    list("1100"),
    list("0100"),
    list("0011"),
    list("1001"),
])
# 3   (top-left block, bottom-right block, the lone cell at the bottom-left)

Grids go up to 300×300 and can be one giant, winding island, so aim for O(rows·cols) and avoid deep recursion (Python's default limit is about 1,000 frames). You may modify grid.

Show hint

Each time you meet land you haven't seen yet, you've found a new island; mark all of it as seen before moving on.

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc