ToolMight Logo
MediumGraphs & Matrix WalksDepth-First Search (DFS)Breadth-First Search (BFS)Connected ComponentsMatrix Flood Fill

Number of Islands

Count disconnected landmasses across a 2D binary grid using connected-component traversal. Compare in-place DFS flood fill against iterative BFS.

Optimal Time
O(m * n)
Optimal Space
O(m * n)
Primary Pattern
Depth-First Search (DFS)
Visualizer
Open Interactive View →

Problem Statement

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Examples & Constraints

Example 1
Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ]
Output: 1
Explanation: All adjacent 1s form a single connected landmass.
Example 2
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ]
Output: 3
Explanation: There are three separate islands disconnected from each other by water.
Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Counting distinct clusters of orthogonally adjacent cells in a matrix reduces directly to counting connected components with DFS, BFS, or Union-Find.

Core Invariant

Whenever a scan hits an unvisited '1', it discovers a brand-new component; exhausting all reachable '1's from that cell before continuing guarantees each island is counted once.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. DFS Flood Fill (In-Place Sink)Optimal
O(m * n)O(m * n)Scan every cell in the grid. Upon finding an unvisited land cell ('1'), increment the island count and recursively sink all horizontally and vertically connected land cells to '0'.
2. Iterative BFS Flood Fill (Queue)
O(m * n)O(min(m, n))Use a FIFO queue to sink reachable land cells level-by-level, eliminating recursive call-stack overflow risk on large grids.

1. DFS Flood Fill (In-Place Sink)

Optimal
TimeO(m * n)
SpaceO(m * n)

Scan every cell in the grid. Upon finding an unvisited land cell ('1'), increment the island count and recursively sink all horizontally and vertically connected land cells to '0'.

Time ComplexityO(m * n)

Every cell in the M x N grid is visited at most a constant number of times (once by the outer nested loop, and once by the DFS recursive sink).

Space ComplexityO(m * n)

In the worst case where the entire grid is land (all '1's), the recursion stack reaches depth M x N.

How It Works

The Connected Component Mental Model

In graph theory, a 2D grid of land and water is an undirected graph where:

  • Each land cell '1' is a vertex.
  • Adjacent horizontal and vertical land cells share an edge.
  • An "island" is a connected component.

The Sinking Technique:

To avoid allocating an m x n auxiliary visited boolean matrix, we can "sink" visited land directly by mutating grid[r][c] = '0':

  1. Iterate over every row r from 0 to m - 1 and column c from 0 to n - 1.
  2. When we encounter grid[r][c] == '1':
  • We have discovered a brand new unvisited island!
  • Increment our total islandCount++.
  • Trigger a DFS flood-fill starting at (r, c) to sink this entire island so we never double-count it.
  1. In the DFS function:
  • Check boundary guards: if r < 0, r >= m, c < 0, c >= n, or grid[r][c] == '0', return immediately.
  • Sink the current cell: grid[r][c] = '0'.
  • Recursively call DFS in all 4 cardinal directions:
  • Up: (r - 1, c)
  • Down: (r + 1, c)
  • Left: (r, c - 1)
  • Right: (r, c + 1)
  1. Return islandCount.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1First Land Cell (0, 0)

Inspect (0, 0) = '1'. Island count = 1. Trigger DFS flood fill to sink connected landmass.

State:islands = 1DFS expanding from (0, 0)
Strengths
  • +Zero auxiliary space overhead for a visited matrix (mutates grid in-place)
  • +Concise 4-directional flood fill logic
Trade-offs
  • -Mutates original grid data
  • -Deep recursion risk on dense 300x300 grids if call stack is small

Reference Implementation

Complete implementation for DFS Flood Fill (In-Place Sink) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def num_islands(grid: list[list[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
def dfs(r: int, c: int) -> None:
if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
return
grid[r][c] = "0" # sink land
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
islands += 1
dfs(r, c)
return islands
if __name__ == "__main__":
grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
print("Number of islands:", num_islands(grid))

2. Iterative BFS Flood Fill (Queue)

TimeO(m * n)
SpaceO(min(m, n))

Use a FIFO queue to sink reachable land cells level-by-level, eliminating recursive call-stack overflow risk on large grids.

Time ComplexityO(m * n)

Every grid cell is enqueued and popped at most once.

Space ComplexityO(min(m, n))

A diagonal BFS wavefront holds at most O(min(m, n)) coordinates in the queue simultaneously.

How It Works

Preventing Recursion Stack Overflow

Recursive DFS uses up to m × n stack frames when an island snakes across the grid (in Python, default recursion limit is ~1,000 frames, far below 300 × 300 = 90,000).

Iterative BFS replaces recursion with an explicit heap-allocated queue:

  1. Scan until grid[r][c] == '1', increment islands++, mark `grid[r][c] = '0'` immediately, and push (r, c) to the queue.
  2. While the queue is non-empty, pop (row, col) and inspect its 4 neighbors.
  3. For each valid neighbor still equal to '1', mark it `'0'` before pushing so no sibling adds duplicate queue entries.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Seed BFS Queue at (0, 0)

Found '1' at (0, 0). Increment islands = 1, sink (0, 0) to '0', push (0, 0).

State:islands = 1queue = [(0,0)]
Strengths
  • +Immune to call-stack overflow on deep winding islands
  • +Lower O(min(m, n)) peak auxiliary queue memory
Trade-offs
  • -Slightly more boilerplate than recursive DFS
  • -Requires O(1) mark-on-enqueue to avoid duplicate pushes

Reference Implementation

Complete implementation for Iterative BFS Flood Fill (Queue) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
from collections import deque
def num_islands_bfs(grid: list[list[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
islands += 1
grid[r][c] = "0"
q = deque([(r, c)])
while q:
cr, cc = q.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
grid[nr][nc] = "0"
q.append((nr, nc))
return islands
if __name__ == "__main__":
sample = [["1","1","0"],["1","0","0"],["0","0","1"]]
print("Islands:", num_islands_bfs(sample))
Interactive Visualizer

Trace BFS & DFS mechanics in memory

Step through custom inputs in the BFS & DFS visualizer to inspect pointer updates, array shifts, and call-stack state alongside Number of Islands.

Open BFS & DFS visualizer

Frequently Asked Questions

Why do we mutate the grid cells to '0' during DFS/BFS?

Marking visited land cells as '0' sinks the cell so subsequent scans and neighbor checks never revisit or double-count the same island, avoiding an extra m x n boolean visited table.

Should I prefer BFS or DFS for Number of Islands?

BFS guarantees O(min(m, n)) queue memory and never hits recursion limits on large grids, making it safer in production or Python interviews; recursive DFS is slightly shorter to write.

Why is marking visited at pop time a bug in BFS?

If you wait until popping a cell from the queue to mark it '0', multiple adjacent cells can push the same neighbor onto the queue before it gets popped, inflating queue size and time complexity.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • All-water grid (every cell '0') returns 0.
  • All-land 300x300 grid returns 1 — recursive DFS reaches depth ~90,000, which can overflow Python/C recursion limits unless BFS is used.
  • Non-rectangular check / single-row or single-column grid (1xN or Mx1).
  • Diagonal cells (e.g., (0,0) and (1,1)) are separate islands unless orthogonal bridges exist.

Common Bugs to Avoid

  • Marking a cell visited when popped in BFS instead of when enqueued — causing the same neighbor to be queued repeatedly and blowing up memory (TLE/MLE).
  • Counting 8-directional diagonals instead of only 4 orthogonal neighbors.
  • Mutating the caller's input grid silently when an interviewer requires read-only preservation.

Interview Follow-Up Variations

  • Preserve the original matrix immutably: store visited coordinates in a boolean array or coordinate set, or restore sentinel values afterward.
  • Number of Islands II (online land additions): use Disjoint Set Union (Union-Find) to merge islands in near-O(1) per query.
  • Find largest island area or distinct island shapes (Max Area of Island / Number of Distinct Islands).

Related Problems

All problems
EasyTrees & BST

Maximum Depth of Binary Tree

Compute the maximum depth (node count along longest root-to-leaf path) of a binary tree using recursive post-order DFS and iterative level-order BFS.

Pattern: Depth-First Search (DFS)
O(n) · O(h)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
MediumGraphs & Matrix Walks

Rotting Oranges

Find minimum minutes for all fresh oranges to rot via 4-directional spreading. Compare in-place O(1)-space round simulation with optimal Multi-Source BFS.

Pattern: Multi-Source BFS
O(m * n) · O(m * n)
Solve