Browse Curriculum
Depth-First Search
Medium

Number of Islands

Count the number of connected groups of 1s in a grid.
Examples
Input:grid = [['1','1','0'], ['1','1','0'], ['0','0','1']]
Output:2
Explain:

Island 1 (Top Left), Island 2 (Bottom Right).

Problem Understanding

Given an m x n map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically.

Algorithm Strategy

We need to find Connected Components.

  1. Iterate: Loop through every cell (r, c) of the grid.
  2. Trigger: If we find a land cell '1', we found a NEW island!
    • Increment count.
    • Sink the Island: Launch DFS from this cell to visit all connected lands and mark them as visited (e.g., change '1' to '0').
  3. Continue: If we see a '0' (or visited cell), skip it.

Visualization

Step 1 / 1

Visualization data missing

Initializing...

1x

Watch as we iterate through the grid. When we hit land, invalidating the entire connected chunk.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.