Count Separated Land Regions in a Binary Matrix
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests graph traversal skills by identifying connected components in a 2D grid using BFS or DFS.
You are given a rectangular matrix of size m × n where each cell contains either the character '1' (representing land) or '0' (representing water).
A land region is a maximal set of land cells where any two cells in the set can reach each other by moving through adjacent land cells. Two cells are adjacent if they share an edge (horizontal or vertical neighbors only; diagonal does not count). The matrix boundaries are treated as water.
Return the total number of distinct land regions in the matrix.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is either'0'or'1'
Examples
Example 1
Input: count_land_regions([['1', '1', '0'], ['1', '1', '0'], ['0', '0', '1']])
Output: 2
Example 2
Input: count_land_regions([['1', '1', '1'], ['0', '1', '0'], ['1', '1', '1']])
Output: 1
Hints
Hint 1
Think of the matrix as a graph where each land cell is a node. What kind of graph problem does counting regions become?
Hint 2
Use BFS or DFS starting from each unvisited land cell to explore an entire region at once.
Hint 3
Mark cells as visited when you add them to your queue or stack, not when you process them, to avoid adding the same cell multiple times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to recognize this as a connected components problem on an implicit graph. Each land cell represents a node, and edges connect horizontally or vertically adjacent land cells. Each land region is one connected component.
The algorithm works in two phases:
- Scan the entire matrix row by row, cell by cell
- When encountering an unvisited land cell, increment the region counter and perform a breadth-first search (BFS) to mark all cells in that connected region as visited
The BFS exploration ensures that every land cell reachable from the starting cell gets marked, preventing it from being counted as a separate region later.
Why This Works
- Completeness: The nested loop visits every cell, so no region can be missed
- No double-counting: Once a region is discovered, BFS marks all its cells as visited before the scan continues, ensuring each region triggers exactly one counter increment
- Correct boundaries: BFS only follows edges to adjacent land cells within bounds, so water and matrix edges naturally separate regions
A critical implementation detail: cells must be marked visited when enqueued, not when dequeued. Marking on dequeue allows the same cell to be added to the queue multiple times by different neighbors, causing unnecessary work.
Complexity
Time: O(m × n)
Each cell is examined once in the outer loop. Each land cell is enqueued and processed at most once during BFS, with each processing checking 4 neighbors. Total operations are linear in grid size.
Space: O(m × n)
The visited matrix requires space proportional to the grid. The BFS queue holds at most O(min(m, n)) cells simultaneously (roughly the width of the wavefront), but the visited matrix dominates.
Note: BFS is preferred over recursive DFS for large grids. A 300×300 grid filled with land could cause recursion depth of 90,000 in DFS, exceeding Python's default limit. Iterative BFS avoids this issue.
Solution Code
from collections import deque
from typing import List
def count_land_regions(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
visited = [[False] * n for _ in range(m)]
regions = 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for r in range(m):
for c in range(n):
if grid[r][c] != '1' or visited[r][c]:
continue
regions += 1
visited[r][c] = True
queue = deque([(r, c)])
while queue:
cr, cc = queue.popleft()
for dr, dc in directions:
nr, nc = cr + dr, cc + dc
if 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] == '1' and not visited[nr][nc]:
visited[nr][nc] = True
queue.append((nr, nc))
return regions