Connected Land Regions in a Matrix
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given an m x n matrix grid whose cells hold either 1 (solid ground) or 0 (open water). Two ground cells belong to the same connected region whenever a path of 1 cells links them using only orthogonal steps — up, down, left, or right. Cells touching only at diagonal corners do not join into a single region.
Implement count_regions(grid: List[List[int]]) -> int to compute how many separate connected ground regions exist in grid (returning 0 when grid is empty or contains only 0s).
Examples
Example 1
Input:
grid = [
[1, 0, 1, 1],
[1, 0, 0, 1],
[0, 1, 0, 0]
]
Output: 3
Walk-through:
- (0, 0) and (1, 0) share a vertical edge, forming one 2-cell region on the left.
- (0, 2), (0, 3), and (1, 3) connect horizontally and vertically into an L-shaped 3-cell region on the upper right.
- (2, 1) meets (1, 0) only diagonally, so it forms a third isolated 1-cell region.
Example 2
Input:
grid = [
[0, 1, 0],
[1, 0, 1],
[0, 1, 0]
]
Output: 4
Walk-through: The four 1 cells at (0, 1), (1, 0), (1, 2), and (2, 1) surround a center 0 and touch only at corners, producing 4 single-cell regions.
Constraints
m == len(grid)andn == len(grid[i])for all0 <= i < m.0 <= m, n <= 300(1 <= m, n <= 300for non-empty matrices; return0ifm == 0orn == 0).- Every entry
grid[i][j]is0or1.
Step-by-step walkthrough
Understand the problem and 4-directional rule
We have an
m x nmatrix of1s (ground) and0s (water). Two ground cells belong to the same region when a path of1s links them through 4-directional moves — up, down, left, or right. Diagonal corners do not merge two regions.Example 1 (answer = 3): Example 2 (answer = 4): [1] 0 [1, 1] <- Region B (L-shape) 0 [1] 0 [1] 0 0 [1] [1] 0 [1] <- touch only at corners: ^-- Region A (2x1) 0 [1] 0 4 separate regions! 0 [1] 0 0 <- Region C (1x1)Empty inputs (
[]or[[]]) contain zero cells and return0.Why a local row-by-row check is not enough
Suppose you tried to count regions in a single top-to-bottom scan by starting a new count whenever a
1has water above it and to its left. Look at what happens on aU-shaped island:Row 0: 1 0 1 <- left arm and right arm look like 2 separate regions! Row 1: 1 0 1 Row 2: 1 1 1 <- bottom row bridges both arms into 1 single regionTwo cells in row
0can connect via a path that dips downward and turns back up many rows later. Instead, model the ground cells as vertices of a graph whose edges connect orthogonally neighboring1s: each region is one connected component (a maximal set of ground cells mutually reachable from one another).Key idea: scan the matrix and flood-fill each unseen island
Walk over every coordinate
(row, col)in row-major order while maintaining aseenboolean matrix of visited ground cells:- If a cell is water (
0) or alreadyseen, skip past it. - If a cell is unseen ground (
1), we have just stepped onto a brand-new region:- Increment
regions += 1. - Flood-fill outward from
(row, col)(visiting orthogonal1neighbors, their1neighbors, and so on) to mark every cell of that islandseen = True.
- Increment
When our outer loop later reaches the remaining cells of that island,
seenis alreadyTrue, so each region is counted exactly once. (Overwriting visited1s with0ingridwould avoid allocatingseen, whereas keepingseenpreserves the caller's matrix.)- If a cell is water (
Code iterative DFS with an explicit stack
How should we run the flood fill? Depth-First Search (DFS) follows connected branches using a stack. Writing DFS recursively is tempting, but on a
300 x 300matrix (90,000cells), a single winding path can stretch45,000+steps — far exceeding Python's default~1,000-frame call stack limit and raisingRecursionError.Using an explicit Python list
stack = [(start_row, start_col)]performs the exact same traversal on heap memory without touching Python's call stack. Two details keepmark_regionbug-free and linear: - Check bounds before indexinggrid[next_row][next_col]: In Python,grid[-1]does not fail — it wraps around to the bottom row! - Setseen[next_row][next_col] = Trueimmediately upon pushing, not when popping. Otherwise, inside a2 x 2block of1s,(1, 1)gets pushed twice before being popped, duplicating work on dense matrices.# DIRECTIONS: (row_delta, col_delta) for up, down, left, right (4-directional adjacency only). DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] def mark_region( grid: List[List[int]], seen: List[List[bool]], start_row: int, start_col: int, ) -> None: # Iterative DFS with an explicit stack avoids Python's ~1000-frame recursion limit on 300x300 snakes. # stack: list of (row, col) land coordinates belonging to this region waiting to expand. rows = len(grid) cols = len(grid[0]) seen[start_row][start_col] = True stack = [(start_row, start_col)] while stack: row, col = stack.pop() for d_row, d_col in DIRECTIONS: next_row = row + d_row next_col = col + d_col in_bounds = 0 <= next_row < rows and 0 <= next_col < cols # Check bounds BEFORE indexing grid[next_row][next_col] so negative indices never wrap around. if in_bounds and grid[next_row][next_col] == 1 and not seen[next_row][next_col]: # Mark seen immediately upon push so multiple neighbors never push the same cell twice. seen[next_row][next_col] = True stack.append((next_row, next_col))Write the outer region counter
In
count_regions, guard against[]and[[]]up front, allocateseenwith[[False] * cols for _ in range(rows)]so every row is an independent list (never[[False] * cols] * rows, which aliases every row to the same list!), and run the outer scan:def count_regions(grid: List[List[int]]) -> int: # Phase 1: Guard against empty grids ([] or [[]]) before reading grid[0]. if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) # seen: m x n boolean matrix tracking which land cells already belong to a counted region. seen = [[False] * cols for _ in range(rows)] regions = 0 # Phase 2: Scan every cell once; each unvisited '1' discovers one brand-new connected region. for row in range(rows): for col in range(cols): if grid[row][col] == 1 and not seen[row][col]: regions += 1 mark_region(grid, seen, row, col) return regionsTrace Example 1 step by step
Matrix: Outer scan events: (0,0)=1 0 (0,2)=1 (0,3)=1 1. At (0,0): unseen '1' -> regions = 1 (1,0)=1 0 0 (1,3)=1 stack=[(0,0)] -> pop (0,0), push & mark (1,0) 0 (2,1)=1 0 0 pop (1,0) -> (2,1) is diagonal, not orthogonal! -> stack=[] 2. At (0,2): unseen '1' -> regions = 2 stack=[(0,2)] -> push & mark (0,3) -> push & mark (1,3) -> stack=[] 3. At (0,3), (1,0), (1,3): already seen -> skipped! 4. At (2,1): unseen '1' -> regions = 3 all 4 orthogonal neighbors are '0' -> stack=[] Return: 3Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # DIRECTIONS: (row_delta, col_delta) for up, down, left, right (4-directional adjacency only). DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] def mark_region( grid: List[List[int]], seen: List[List[bool]], start_row: int, start_col: int, ) -> None: # Iterative DFS with an explicit stack avoids Python's ~1000-frame recursion limit on 300x300 snakes. # stack: list of (row, col) land coordinates belonging to this region waiting to expand. rows = len(grid) cols = len(grid[0]) seen[start_row][start_col] = True stack = [(start_row, start_col)] while stack: row, col = stack.pop() for d_row, d_col in DIRECTIONS: next_row = row + d_row next_col = col + d_col in_bounds = 0 <= next_row < rows and 0 <= next_col < cols # Check bounds BEFORE indexing grid[next_row][next_col] so negative indices never wrap around. if in_bounds and grid[next_row][next_col] == 1 and not seen[next_row][next_col]: # Mark seen immediately upon push so multiple neighbors never push the same cell twice. seen[next_row][next_col] = True stack.append((next_row, next_col)) def count_regions(grid: List[List[int]]) -> int: # Phase 1: Guard against empty grids ([] or [[]]) before reading grid[0]. if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) # seen: m x n boolean matrix tracking which land cells already belong to a counted region. seen = [[False] * cols for _ in range(rows)] regions = 0 # Phase 2: Scan every cell once; each unvisited '1' discovers one brand-new connected region. for row in range(rows): for col in range(cols): if grid[row][col] == 1 and not seen[row][col]: regions += 1 mark_region(grid, seen, row, col) return regions✅ Submit now — all tests should pass.
Intuition & how it works
Imagine looking down at a pixel map of islands (1) and water (0), holding a dropper of dye that spreads across touching up, down, left, and right ground tiles while stopping at water and diagonal corners. As you scan the map tile by tile and squeeze one drop onto every undyed ground tile you encounter, that drop floods across the entire connected island — a graph traversal technique called flood fill (implemented here via iterative Depth-First Search, or DFS, which expands connected neighbors using a last-in-first-out stack) — so the count of drops squeezed equals the island count.
Why do simpler approaches fall short? Counting islands in one top-to-bottom scan that checks only the neighbor above and to the left miscounts U-shaped islands, whose two upper arms appear disconnected until a bottom row bridges them later. Recursive DFS handles connectivity on small inputs, yet on a 300 x 300 matrix (90,000 cells) a winding path can run 45,000+ cells deep, crashing Python's ~1,000-frame call stack with RecursionError — whereas an explicit stack list lives on heap memory and scales effortlessly.
Here is how the scan processes Example 1 ([[1, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 0]]):
Matrix: (0,0)=1 (0,1)=0 (0,2)=1 (0,3)=1
(1,0)=1 (1,1)=0 (1,2)=0 (1,3)=1
(2,0)=0 (2,1)=1 (2,2)=0 (2,3)=0
1. Visit (0,0)=1 (unseen) -> regions = 1; DFS marks (0,0) and (1,0) as seen.
2. Visit (0,2)=1 (unseen) -> regions = 2; DFS marks (0,2), (0,3), and (1,3) as seen.
3. Skip (0,3), (1,0), (1,3) (already seen) and all 0 cells.
4. Visit (2,1)=1 (unseen; touches (1,0) only diagonally!) -> regions = 3; DFS marks (2,1).
Result: 3 regions.
Complexity
- Time:
O(m * n), formrows andncolumns. The outer loop checks each of them * ncells once, and because every ground cell is markedseen = Trueas soon as it entersstack, each cell is pushed and popped at most once across the entire call, doing4constant-time neighbor checks when popped. - Space:
O(m * n). Theseentable holdsm * nbooleans, and in the worst casestackstoresO(m * n)coordinates simultaneously. (Overwriting visited1s with0insidegridremovesseen, though worst-casestackmemory remainsO(m * n).)
Edge cases
- Empty matrix (
[]or[[]]): Caught immediately byif not grid or not grid[0]:, returning0withoutIndexError. - All water (
[[0, 0], [0, 0]]):mark_regionnever runs and0is returned. - Single cell (
[[1]]or[[0]]): Returns1for ground and0for water. - All ground (
300 x 300of1s): The very first flood fill marks all90,000cells and returns1. - Diagonal-only neighbors (Example 2): Diagonal offsets are absent from
DIRECTIONS, so the4corner-touching1s stay4separate regions. - Long winding snake (
45,000+cells on300 x 300): Explicitstackfinishes cleanly withoutRecursionError. - Island inside a lake inside a ring island: Water blocks the outer flood fill, leaving the inner island unseen until the scan reaches and counts it separately.
Common mistakes
- Using recursive DFS without accounting for Python's recursion limit: On a
300 x 300serpentine island, recursion depth reaches~45,000and raisesRecursionError. - Marking
seenonpopinstead of onpush: Delayingseen[r][c] = Trueuntilstack.pop()lets multiple neighbors push duplicate copies of(r, c)ontostack, inflating memory and runtime on dense matrices. - Forgetting
0 <= next_rowand0 <= next_colbefore indexing: In Python,grid[-1][col]is valid syntax that reads the last row, falsely connecting islands across opposite edges of the matrix! - Allocating
seenwith[[False] * cols] * rows: Multiplying the outer list makes every row point to the same inner list object, so marking(0, 2)marks column2in every row. Always write[[False] * cols for _ in range(rows)]. - Including diagonal offsets in
DIRECTIONS: Adding(+-1, +-1)merges corner-touching cells and returns1instead of4on Example 2.
Alternative approaches
- Breadth-First Search (BFS): Replace
stack.pop()withqueue.popleft()on acollections.deque(expanding cells in concentric distance rings rather than deep paths). Runtime staysO(m * n)while worst-case queue size drops toO(min(m, n))! - Union-Find (Disjoint-Set Union): A parent-pointer structure supporting
find(with path compression) andunionin nearlyO(1)amortized time per step. Union each1cell with its right and bottom1neighbors, then count distinct component roots.
Follow-up questions
- What changes if cells touching diagonally (8-directional adjacency) also merge into the same region? Extend
DIRECTIONSfrom4orthogonal pairs to all8surrounding offsets by adding(-1, -1),(-1, 1),(1, -1), and(1, 1). Every other line ofmark_regionandcount_regionsstays unchanged, and both time and space remainO(m * n)(8neighbor checks per ground cell instead of4, merging Example 2's four diamond cells into1single region). - How do the runtime and auxiliary memory scale with the matrix dimensions m and n? Runtime scales as
O(m * n)because the outer loops inspect allm * ncells once and each1cell enters and leavesstackat most once withO(1)work per neighbor. Auxiliary memory scales asO(m * n)for them x nseentable plusO(m * n)worst-casestackdepth (switching to BFS withcollections.dequeand mutatinggridin place lowers auxiliary memory toO(min(m, n))). - Suppose the matrix resides on disk and cannot fit in RAM—how could you count regions by streaming rows or processing fixed-size tiles? Use Union-Find (a parent-pointer table tracking and merging component IDs) while streaming one row at a time in
O(n)RAM: give each1in the current row either its left neighbor's ID (when left is1) or a fresh ID (regions += 1), and whenever the cell directly above inprev_rowis also1with a different root ID, union the two roots and decrementregions -= 1. After finishing each row, rewritecur_rowlabels to their canonical roots and drop all parent entries absent fromcur_rowso memory staysO(n). For 2D disk tiles (B x Bblocks), count internal regions inside each tile independently, retain only the component IDs along each tile's4borders (O(B)memory per tile instead ofO(B^2)), and run Union-Find across shared tile borders (total = sum(tile_counts) - border_merges).
def count_regions_streaming(rows):
"""Stream an arbitrarily tall matrix row by row using O(n) memory."""
parent = {}
def find(label):
while parent[label] != label:
parent[label] = parent[parent[label]]
label = parent[label]
return label
regions = 0
next_label = 0
prev_row = None
for row in rows:
cur_row = [None] * len(row)
for col, cell in enumerate(row):
if cell != 1:
continue
if col > 0 and cur_row[col - 1] is not None:
cur_row[col] = cur_row[col - 1]
else:
cur_row[col] = next_label
parent[next_label] = next_label
next_label += 1
regions += 1
if prev_row is not None and prev_row[col] is not None:
root_a = find(cur_row[col])
root_b = find(prev_row[col])
if root_a != root_b:
parent[root_a] = root_b
regions -= 1
# Compact active labels to their current roots so forgotten rows take zero RAM.
for col, label in enumerate(cur_row):
if label is not None:
cur_row[col] = find(label)
parent = {label: label for label in cur_row if label is not None}
prev_row = cur_row
return regions
Follow-up questions
- What changes if cells touching diagonally (8-directional adjacency) also merge into the same region?
- How do the runtime and auxiliary memory scale with the matrix dimensions m and n?
- Suppose the matrix resides on disk and cannot fit in RAM—how could you count regions by streaming rows or processing fixed-size tiles?
Similar questions
- Clockwise Spiral Order and Two-Sum Check
- Distributed Time-Series Metrics Database
- Cross-Cloud Data Synchronization and Unified API Gateway
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses