LC 200
LeetCode 200 · Medium

Number of Islands

Count islands (4-connected groups of land) in a grid of 1s and 0s.

DFS → · Very high frequency · Solve on LeetCode →

Try it

Step through the core mechanic. The simulator below runs the dfs shape this problem is built on.

Interactive · grid flood-fill
~
~
~
~
~
~
~
~
~
~
stack (bottom → top)
(0,0)
seed the stack with the start cell (0,0)
step 1 / 5
BFS vs DFS, same grid. Swap the frontier from a queue to a stack and breadth-first becomes depth-first. Both visit exactly the same cells; only the order differs. BFS layers outward (shortest-path / wave problems); DFS plunges down one branch (component / path problems).

The approach

Scan the grid; on each unvisited land cell, flood-fill (DFS or BFS) the whole island to mark it visited, then increment the count. Each cell is touched once.

AspectValue
PatternDFS
Recognise it byCount connected components on a grid.
Time complexityO(mn)
Space complexityO(mn)
DifficultyMedium

Who asks it

Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.