Connected Land Regions in a Character Matrix
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests graph traversal and connected-component identification on a 2D grid using flood-fill techniques.
You receive an m × n matrix of characters in which every cell holds either '1' (representing land) or '0' (representing water). A region is a maximal set of land cells connected through horizontal or vertical adjacency; diagonal connections do not join cells into the same region. The perimeter of the matrix is treated as water.
Write a function that computes how many distinct land regions exist in the matrix.
Parameters
matrix: a 2D list of strings, where each string is'0'or'1'
Return Value
An integer representing the count of disconnected land regions.
Constraints
1 ≤ m, n ≤ 300- Every cell is either
'0'or'1'
Examples
Example 1
Input: count_land_regions([['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']])
Output: 3
Hints
Hint 1
Model the matrix as a graph where each land cell is a vertex and edges connect orthogonally adjacent land cells. The answer is the number of connected components in this graph.
Hint 2
Iterate through every cell; when you encounter an unvisited land cell, you have discovered a new region. Use depth-first or breadth-first traversal to mark all cells in that region as visited.
Hint 3
Mark cells as visited when you add them to your traversal structure (stack or queue), not when you process them, to avoid redundant work and excessive memory usage.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The matrix defines an implicit graph: each land cell is a node, and edges exist between land cells that share a horizontal or vertical boundary. A region corresponds to a connected component in this graph, so the task reduces to counting connected components.
The algorithm combines a full grid scan with flood-fill exploration:
- Traverse every cell in the matrix in row-major order.
- When you encounter a land cell (
'1') that has not yet been visited, increment the region counter and initiate a flood-fill from that cell. - The flood-fill uses an explicit stack (iterative depth-first search) to explore all reachable land cells in four directions (up, down, left, right), marking each as visited to prevent revisiting.
- Continue the scan. Cells already marked as visited belong to a region that has already been counted.
A separate visited matrix tracks which cells have been processed, preserving the original input.
Correctness
The algorithm guarantees each region is counted exactly once:
-
Every region is counted: The scan visits all cells. Each region contains at least one land cell. When the scan first reaches any cell in a previously undiscovered region, that cell cannot have been visited yet (earlier flood-fills only mark cells reachable from their starting points, and regions are disconnected by definition). The counter increments, and the flood-fill marks the entire region.
-
No region is counted twice: Once a region is discovered, the flood-fill marks every cell in that connected component. The flood-fill expands to all orthogonally adjacent unvisited land cells, recursively covering the entire component. Subsequent scan positions inside that region skip the increment because those cells are already visited.
Marking cells as visited at push time (when added to the stack) rather than at pop time ensures each cell enters the stack at most once, avoiding redundant processing.
Why Iterative DFS
Given the constraint m, n ≤ 300, a single region could span up to 90,000 cells (e.g., a snake-shaped pattern filling the grid). Recursive DFS would reach a recursion depth near 90,000, far exceeding Python's default limit of approximately 1,000 frames, risking a RecursionError. An explicit stack avoids recursion depth issues entirely while maintaining the same traversal logic.
Complexity
Time: O(m · n). The outer scan visits each of the m · n cells once. Each land cell is pushed to the stack and popped at most once, and each pop inspects four neighbors. Total work across all flood-fills is O(m · n).
Space: O(m · n). The visited matrix requires m · n boolean values. In the worst case (a single region covering the entire grid), the stack can hold O(m · n) cells.
Full Solution
from typing import List
def count_land_regions(matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
visited = [[False] * cols for _ in range(rows)]
count = 0
for r in range(rows):
for c in range(cols):
if matrix[r][c] != '1' or visited[r][c]:
continue
count += 1
visited[r][c] = True
stack = [(r, c)]
while stack:
curr_r, curr_c = stack.pop()
for next_r, next_c in ((curr_r - 1, curr_c), (curr_r + 1, curr_c),
(curr_r, curr_c - 1), (curr_r, curr_c + 1)):
if (0 <= next_r < rows and 0 <= next_c < cols
and matrix[next_r][next_c] == '1'
and not visited[next_r][next_c]):
visited[next_r][next_c] = True
stack.append((next_r, next_c))
return count