Algorithms · Visualized
Matrix: Number of Islands
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Given a grid of land ('1') and water ('0'), counts how many separate islands exist, where an island is a group of land cells connected horizontally or vertically. Time: O(rows × cols) average, O(rows × cols) — every cell visited once worst; space: O(rows × cols) — recursion/queue in the worst case (one giant island).
Big-O: Classic O(m·n) sweeps and in-place tricks.
Number of Islands
Matrix / 2D ArrayGiven a grid of land ('1') and water ('0'), counts how many separate islands exist, where an island is a group of land cells connected horizontally or vertically. Each time an unvisited land cell is found, it's the start of a new island — a flood-fill (DFS or BFS) marks the entire connected island as visited before moving on.
How Number of Islands Works
- Loop through every cell in the grid.
- Whenever you find a land cell ('1') that hasn't been visited yet, increment the island count by 1 — you've found a new island.
- Immediately run a flood-fill (DFS or BFS) from that cell, visiting all connected land cells (up, down, left, right) and marking each as visited (e.g. by changing '1' to '0' or using a separate visited set).
- This ensures the rest of that same island won't be counted again as a 'new' island later in the scan.
- Continue scanning the rest of the grid; the final island count is the answer.
Number of Islands Worked Example
Input: [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
Scan finds land at (0,0) → flood-fill marks the connected block (0,0),(0,1),(1,0),(1,1) as visited, island count=1. Continue scanning, finds land at (2,2) → flood-fill marks just that cell, island count=2. Continue, finds land at (3,3) → flood-fill marks just that cell, island count=3. Total islands: 3.
def num_islands(grid):
def dfs(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != '1':
return
grid[r][c] = '0'
dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1)
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
count += 1
dfs(r, c)
return countBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Number of Islands Time & Space Complexity
When to Use Number of Islands
- Geographic/GIS mapping: counting distinct landmasses or regions from satellite grid data.
- Network/cluster analysis: counting connected components in any grid-like connectivity structure.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.