Count separate islands of land in a rectangular grid where only side-sharing cells are connected.
Problem
Input. A rectangular grid of independent mutable rows containing string cells "1" for land and "0" for water.
Output. Return the number of connected land regions, not the number of land cells.
Rules. Land connects only through up, down, left, and right neighbors, not diagonally.
The reference consumes land by changing visited "1" cells to "0".
Use strings rather than integer cells. Empty input returns zero.
Example. Build rows with [list(row) for row in ["1100", "0101", "1001", "1011"]]:
1100
0101
1001
1011
Return 3, not the nine land cells. The reference leaves this grid containing only water.
Picture
Imagine covering an entire connected patch when its first uncovered cell is found. Later scan positions inside that patch cannot start another island.
| First unseen seed | Component cells | Running count |
|---|---|---|
(0,0) | 3 | 1 |
(1,3) | 4 | 2 |
(2,0) | 2 | 3 |
Problem trace
Separate shared-cell case: mark before scheduling a second discovery
Reference drawing
Problem trace
Mark each land cell before scheduling its neighbors
Execution trace
- DFS top
- (0, 0)
- input
- 4x4 grid; 4-neighbor land only
- stack
- [(0,0)]
- visited
- not shown→(0, 0)
- visited
- not shown→(0, 1)
- visited
- not shown→(1, 1)
- DFS top
- not shown→(1, 3)
- stack
- empty→[(1,3)]
- islands
- 1→2
- visited
- not shown→(1, 3)
- visited
- not shown→(2, 3)
- DFS top
- (1, 3)→(3, 3)
- visited
- not shown→(3, 3)
- visited
- not shown→(3, 2)
- DFS top
- (3, 3)→not shown
- visited
- not shown→(2, 0)
- DFS top
- not shown→(3, 0)
- stack
- empty→[(3,0)]
- visited
- not shown→(3, 0)
- DFS top
- (3, 0)→not shown
- stack
- [(3,0)]→empty
- Recognize it
- The task asks for connected groups in a binary grid under four-direction adjacency, so every unseen land cell identifies exactly one not-yet-counted component.
- Keep true
- Before the scan advances, every visited land cell has been changed to 0; each stack contains only cells from the current island, and each completed island can never be counted again.
- Reuse it
- For regions, blobs, and connected-component problems, scan for unseen seeds, count seeds rather than cells, and exhaustively mark each seed’s reachable component before continuing.
Mark a seed before placing it on the stack. Mark each new neighbor before pushing it, too. Every land cell is therefore scheduled once, even when several neighbors could discover it. Stack order changes visitation order, not component membership.
Code
def num_islands(grid: list[list[str]]) -> int:
islands = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] != "1":
continue
islands += 1
grid[row][col] = "0"
stack = [(row, col)]
while stack:
current_row, current_col = stack.pop()
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
new_row = current_row + row_step
new_col = current_col + col_step
if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]):
if grid[new_row][new_col] == "1":
grid[new_row][new_col] = "0"
stack.append((new_row, new_col))
return islands
Scanning and coverage take time.
The explicit stack can require auxiliary space.
There is no logarithmic-stack guarantee.
Empty and zero-width grids return 0.
Failure Check
The diagonal grid ["10","01"] has two islands under this adjacency rule.
Counting each popped cell returns area, not island count.
Restoring marks would allow later scan positions to count the same component again.
Change the Ownership
New task: Count islands without changing the caller’s grid.
Picture and change: Copy each row before destructive coverage. The wrapper also accepts string rows by converting them to mutable character lists.
def islands_preserving(grid):
return num_islands([list(row) for row in grid])
Check: The source still returns 3, with all original cells unchanged.
The copy adds storage.
Use when: Mutation permission changes, not connectivity.
Change the Reduction
New task: Return the largest island area.
Picture and change: Keep permanent discovery marks, count cells within each completed flood, then maximize those counts. This version still consumes mutable string-cell rows.
def largest_island_area(grid):
best = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] != "1":
continue
grid[row][col] = "0"
stack, area = [(row, col)], 0
while stack:
current_row, current_col = stack.pop()
area += 1
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_row, next_col = current_row + row_step, current_col + col_step
if 0 <= next_row < len(grid) and 0 <= next_col < len(grid[0]):
if grid[next_row][next_col] == "1":
grid[next_row][next_col] = "0"
stack.append((next_row, next_col))
best = max(best, area)
return best
Check: Source component areas are 3,4,2, so return 4.
No land returns 0.
Time and worst-case stack bounds remain unchanged.
Use when: Component size, not the number of components, is requested.
Transfer Check
Why keep marks permanently here but undo used-cell marks in a word-search branch?
Answer
Component membership is a global completed fact. A candidate path’s used cells constrain only that path; other paths must be allowed to try them again. Compare reversed reachability when the task asks which goals each cell can reach.