TRT
Sign in
mediumAdvancedLeetCode#flood fill#grid DFS

Number of islands

Count the islands in a grid of land and water, flooding each one with DFS or BFS the first time you step on it.

The Runtime Theory Team1 min read
Taught inDepth-first searchPro — members onlyDepth-first search follows one path as far as it can, then backs up and tries the next. It is the natural way to flood a region, explore every possibility, or ask what is reachable, as long as you watch its depth.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ingrid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]

out3

ingrid = [[1]]

out1

ingrid = [[0]]

out0

Given a grid of "1" (land) and "0" (water), return the number of islands: groups of land cells connected horizontally or vertically.

Before you code

Scan the grid. Every time you meet land you haven't seen, you have found a new island, and a flood fill from there marks all of it.

Hints

  1. Count, then flood with DFS, changing "1" to "0" (or another mark) as you go.
  2. Mark a cell before recursing into its neighbors.
  3. For very large grids, use an explicit stack or BFS to avoid deep recursion.

Production & complexity notes

When solving Number of islands on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Depth-first search to reinforce the underlying pattern.

What it practices

Flood fill and counting regions, from Depth-first search.

Not started

Sign in to save your learning progress.

Sign in to save