← Practice
πŸ“– Graphsgraphs-num-islands
LessonΒ·difficulty 4/5Β·~24 min

Graphs: number of islands

Graphs: number of islands

You're given a grid where 1 is land and 0 is water. An island is a group of 1s connected horizontally or vertically (not diagonally). Count the islands.

A grid is just a graph in disguise: each land cell is a node, and edges connect it to its up/down/left/right land neighbours. Counting islands means counting connected components.

The standard tool is flood fill: walk over every cell; when you hit a land cell you haven't seen, that's a new island β€” then DFS/BFS out to mark every land cell reachable from it as visited so you don't count it again.

python
for each cell (r, c):
    if grid[r][c] == 1 and (r, c) not in seen:
        count += 1
        flood_fill(r, c)   # mark this whole island as seen

Your task

Write num_islands(grid) where grid is a list of lists of ints. Return the number of islands. Track visited cells in a set (don't mutate the caller's grid β€” the function may be called more than once on the same grid).

python
num_islands([[1, 1, 0], [0, 1, 0], [0, 0, 1]])  # 2
num_islands([[0, 0], [0, 0]])                     # 0
num_islands([[1]])                                # 1

Hint: a seen set of (row, col) tuples plus a stack (DFS) or collections.deque (BFS) makes the flood fill straightforward.

Tests

  • two islands
  • all water
  • single cell
  • one big island
  • row of three (hidden)
  • callable twice (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.