Count Regions in a Binary Grid
IllumioSoftware Engineer · OnsiteLast updated
This problem tests your ability to navigate a 2D grid and identify connected components using graph traversal techniques like Depth-First Search (DFS) or Breadth-First Search (BFS).
Problem Statement
Given an m x n binary grid grid where 1 represents land and 0 represents water, a region is defined as a group of 1s connected 4-directionally (horizontally or vertically). Write a function to return the total number of distinct regions in the grid.
Function Signature
def count_regions(grid: list[list[int]]) -> int:
Examples
Example 1: Input:
grid = [
[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
Output: 3
Explanation: There are two regions of connected 1s on the top left and two individual 1s on the bottom right diagonal.
Example 2: Input:
grid = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
Output: 5
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is either0or1.
Edge Cases
- An empty grid or a grid with no
1s. - A grid filled entirely with
1s. - Grids with a single cell.
Hints
Hint 1
You can treat the grid as an undirected graph where each '1' cell is a node, and adjacent '1' cells share an edge.
Hint 2
Iterate through every cell in the grid; when you encounter a '1', trigger a traversal to mark all connected '1's as visited.
Hint 3
To save space, you can modify the input grid directly to '0' once a cell is visited, rather than using an auxiliary visited set.
Follow-up questions
- How would your approach change if diagonal connections were also considered part of a region?
- What is the time and space complexity of your solution in terms of m and n?
- If the grid were too large to fit into memory, how would you approach counting regions using a streaming or block-based strategy?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.