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 Array

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. 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

  1. Loop through every cell in the grid.
  2. 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.
  3. 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).
  4. This ensures the rest of that same island won't be counted again as a 'new' island later in the scan.
  5. 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.

Matrix: Number of IslandsO(m·n)
Count connected groups of land cells using DFS.
1
1
0
0
1
1
0
0
0
0
1
0
0
0
0
1
islands0
Step 1 / 11
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Number of Islands: count connected groups of "1" cells (4-directional neighbours).
Python · Matrix Algorithms in Code
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 count

Behind 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

BestO(rows × cols)
AverageO(rows × cols)
WorstO(rows × cols) — every cell visited once
SpaceO(rows × cols) — recursion/queue in the worst case (one giant island)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.