progress

~/problems / Graphs / DFS and connected components

Number of Islands

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

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 avoid deep recursion (Python's default limit is about 1,000 frames). You may modify grid.

⭐ Bonus: speed tests on 300×300 grids earn a star in O(rows·cols).

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