Full answer
Problem
Given an R x C grid of '1' and '0', return the number of islands. An island is a maximal group of land cells connected up, down, left or right (not diagonally).
Example:
11000
11000
00100
00011
has 3 islands.
Constraints: 1 <= R, C <= 300.
Brute force
For every land cell, run a fresh search to collect its island, then deduplicate islands by comparing cell sets. Repeated searches make this O((R * C)^2) in the worst case.
Optimal approach
Flood fill:
- Copy the grid (or keep a visited set) so the input is not modified.
- For each cell that is
'1': count += 1, mark it'0', and BFS through its land neighbours, marking each when it is enqueued.
Union-find alternative: create a set per land cell and union each with its land neighbours above and to the left; the answer is the number of distinct roots.
Why it works
The grid is a graph whose nodes are land cells and whose edges join 4-adjacent land cells; an island is a connected component. Each flood fill marks one entire component, so every later scan step that finds unmarked land is in a new component.
Complexity
O(R * C) time: each cell is examined by the scan and enqueued at most once. Space O(R * C) for the copy, plus O(min(R, C)) to O(R * C) for the BFS queue. Recursive DFS can reach depth R * C on a snake-shaped island, which exceeds Python's recursion limit, so BFS or an explicit stack is safer.
Code
import random
from collections import deque
def num_islands(grid):
"""Count 4-connected groups of '1'. BFS flood fill, O(R * C) time.
Works on a copy so the caller's grid is not modified."""
if not grid:
return 0
g = [row[:] for row in grid]
rows, cols, count = len(g), len(g[0]), 0
for r in range(rows):
for c in range(cols):
if g[r][c] != "1":
continue
count += 1
g[r][c] = "0" # sink on enqueue so no cell is queued twice
q = deque([(r, c)])
while q:
y, x = q.popleft()
for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
if 0 <= ny < rows and 0 <= nx < cols and g[ny][nx] == "1":
g[ny][nx] = "0"
q.append((ny, nx))
return count
def num_islands_uf(grid):
"""Union-find version: useful when land is added cell by cell."""
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
parent = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
parent[(r, c)] = (r, c)
for p in ((r - 1, c), (r, c - 1)):
if p in parent:
parent[find(p)] = find((r, c))
return len({find(p) for p in parent})
if __name__ == "__main__":
grid = [list("11000"), list("11000"), list("00100"), list("00011")]
assert num_islands(grid) == num_islands_uf(grid) == 3
assert grid[0][0] == "1" # input untouched
assert num_islands([]) == 0 and num_islands([list("0")]) == 0
assert num_islands([list("101"), list("010"), list("101")]) == 5 # diagonals do not connect
rng = random.Random(67)
for _ in range(500):
r, c = rng.randint(1, 8), rng.randint(1, 8)
g = [[rng.choice("01") for _ in range(c)] for _ in range(r)]
assert num_islands(g) == num_islands_uf(g)
print("all tests passed")Save as b67_islands.py and run python3 b67_islands.py. It prints all tests passed (Python 3.13.5).
Edge cases
All water (0). All land (1). Diagonal touching does not connect (the checkerboard test has 5 islands). Single row or column. Mutating the caller's grid is often unacceptable; say whether the input may be modified.
Pattern
Connected components on a grid via flood fill. Related problems: max area of island, surrounded regions, number of distinct island shapes (record the path signature), and "number of islands II" where cells turn to land one by one, which needs union-find.
import random
from collections import deque
def num_islands(grid):
"""Count 4-connected groups of '1'. BFS flood fill, O(R * C) time.
Works on a copy so the caller's grid is not modified."""
if not grid:
return 0
g = [row[:] for row in grid]
rows, cols, count = len(g), len(g[0]), 0
for r in range(rows):
for c in range(cols):
if g[r][c] != "1":
continue
count += 1
g[r][c] = "0" # sink on enqueue so no cell is queued twice
q = deque([(r, c)])
while q:
y, x = q.popleft()
for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
if 0 <= ny < rows and 0 <= nx < cols and g[ny][nx] == "1":
g[ny][nx] = "0"
q.append((ny, nx))
return count
def num_islands_uf(grid):
"""Union-find version: useful when land is added cell by cell."""
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
parent = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
parent[(r, c)] = (r, c)
for p in ((r - 1, c), (r, c - 1)):
if p in parent:
parent[find(p)] = find((r, c))
return len({find(p) for p in parent})
if __name__ == "__main__":
grid = [list("11000"), list("11000"), list("00100"), list("00011")]
assert num_islands(grid) == num_islands_uf(grid) == 3
assert grid[0][0] == "1" # input untouched
assert num_islands([]) == 0 and num_islands([list("0")]) == 0
assert num_islands([list("101"), list("010"), list("101")]) == 5 # diagonals do not connect
rng = random.Random(67)
for _ in range(500):
r, c = rng.randint(1, 8), rng.randint(1, 8)
g = [[rng.choice("01") for _ in range(c)] for _ in range(r)]
assert num_islands(g) == num_islands_uf(g)
print("all tests passed")BFS flood fill on a copy and a union-find version; random grids cross-check the two.
Complexity
Time: O(R * C). Space: O(R * C). Union-find with path compression is effectively linear and handles online additions.
By level
Fresher: Scans the grid and flood-fills each new island with BFS or DFS, explaining why diagonals do not count. States O(R * C).
Mid: Uses an explicit queue to avoid recursion limits, keeps the input unchanged, and offers union-find. Adapts to largest-area and distinct-shape variants.
Senior: Discusses the online version with union-find, very large grids processed in tiles with boundary merging, and memory layout for grid scans. Relates the problem to image segmentation and map region labelling.
Key points
- Islands are connected components of a grid graph
- Count one per new flood fill
- Mark on enqueue
- 4-directional only unless told otherwise
- BFS avoids recursion depth issues
Common mistakes
- Counting diagonal neighbours
- Recursing on large grids in Python
- Modifying the input without asking
- Marking on dequeue, causing duplicate enqueues
Follow-ups
- How do you return the largest island area?
- How would you handle cells turning into land one at a time?
- How would you count distinct island shapes?
Tips
- Ask whether the grid may be modified
- Mention the recursion risk
- Offer union-find for the dynamic version
Evaluation rubric
- Correct component count
- Correct neighbour rule
- O(R * C)
- Discusses mutation and recursion