CODING CHALLENGE · N°25

Number of Islands

Medium GraphsBFS/DFSInterview Classic

The canonical connected-components question — asked at every company that has ever run an interview. Flood-fill each unvisited patch of land, count how many times you had to start a flood. Grid traversal, visited bookkeeping, no tricks.

The problem

Given grid, a 2D list of 0s (water) and 1s (land), return the number of islands — groups of 1s connected horizontally or vertically (not diagonally). Traverse each island once with BFS or DFS, marking cells visited so no island is counted twice.

EXAMPLE 1
Input grid = [[1,1,0],[0,1,0],[0,0,1]]
Output 2
the L-shape is one island; the corner cell is another
EXAMPLE 2
Input grid = [[1,0],[0,1]]
Output 2
diagonal does NOT connect
EXAMPLE 3
Input grid = [[0,0],[0,0]]
Output 0
all water
CONSTRAINTS
  • Connectivity is 4-directional (up, down, left, right).
  • Do not count an island more than once — mark visited cells.
  • The grid may be empty; return 0.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement num_islands(grid) → the count of 4-connected groups of 1s, using BFS or DFS with a visited set (or by sinking visited land in a copy).

HINTS — 4 IDEAS
  1. Scan every cell; when you find an unvisited 1, increment the count and flood from it.
  2. Flood with an explicit stack or queue: pop a cell, push its 4 unvisited land neighbours.
  3. Mutating a copy of the grid (set visited land to 0) is the simplest visited set.
  4. Bounds-check before you look: r in [0, rows), c in [0, cols).
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.