Count Separate Land Regions in a Grid
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests flood-fill traversal to identify connected components in a 2D grid with four-directional adjacency.
You are given a 2D grid represented as a list of lists, where each cell contains either the character '1' (representing land) or '0' (representing water).
Your task is to determine how many separate land regions exist in the grid. A land region is formed by land cells that are connected through shared edges—specifically, cells are considered connected if they are adjacent horizontally or vertically (up, down, left, or right). Cells that touch only at their corners (diagonally) do not belong to the same region.
Write a function that returns the total count of distinct land regions.
Constraints:
- The grid may be
None, empty, or contain empty rows 0 ≤ rows, cols ≤ 1000- Each cell is either the string
'1'or'0' - Adjacency is defined as sharing an edge (4-directional connectivity only)
- The input grid should not be modified
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
Example 2
Input: count_land_regions([['1', '1', '0'], ['0', '1', '0'], ['0', '0', '1']])
Output: 2
Example 3
Input: count_land_regions([['1', '0', '1'], ['0', '1', '0'], ['1', '0', '1']])
Output: 5
Hints
Hint 1
Think of the grid as a graph where land cells are nodes. What graph algorithm finds all connected components?
Hint 2
When you encounter an unvisited land cell, you've discovered a new region. How can you mark all cells in that region to avoid counting them again?
Hint 3
Consider using a queue-based traversal to explore each region. Mark cells as visited when you add them to the queue, not when you remove them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to count connected components in an undirected graph where land cells are vertices and edges connect cells that share a side.
We iterate through every cell in the grid. When we find a land cell that hasn't been visited yet, we've discovered a new region. We increment our counter and then perform a complete traversal of that region, marking every reachable land cell as visited so we don't count it again.
Breadth-first search works well for this traversal. We use a queue to explore the region level by level, adding each unvisited neighbor to the queue as we discover it. The key optimization is to mark cells as visited when we add them to the queue, not when we process them—this prevents the same cell from being enqueued multiple times.
We maintain a separate visited set rather than modifying the input grid, which preserves the original data structure for the caller.
Why It Works
- Every land cell is examined by the outer loop scan
- The first time we encounter any cell from a region, we traverse and mark the entire region
- Subsequent encounters with cells from that region skip them because they're already in the visited set
- Only the four cardinal directions are explored, so diagonal touches don't create connections
- Each region is counted exactly once
Complexity
Time: O(m × n) where m is the number of rows and n is the number of columns. Each cell is visited at most once, and each visit examines four neighbors with constant-time operations.
Space: O(m × n) in the worst case. The visited set can contain all cells, and the queue can grow to hold an entire region (potentially the full grid if all cells are land).
Solution
from collections import deque
from typing import List, Optional
def count_land_regions(grid: Optional[List[List[str]]]) -> int:
if not grid or not grid[0]:
return 0
rows = len(grid)
cols = len(grid[0])
visited = set()
regions = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != '1' or (r, c) in visited:
continue
regions += 1
visited.add((r, c))
queue = deque([(r, c)])
while queue:
cr, cc = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '1' and (nr, nc) not in visited:
visited.add((nr, nc))
queue.append((nr, nc))
return regions