Number of Islands

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Number of Islands

Approach

Visit every cell. When land is found, run DFS to mark every connected land cell as water. Increment a counter only for a new starting land component.

Complexity Analysis

Time
O(m * n)
Space
O(m * n)

Pattern

Graph as Grid Components

Why It Works

Every island is a connected region. Once DFS marks all cells in one island as visited, remaining unvisited land must belong to a new island.

Updated Feb 2026