KatInterview

Count Connected Land Regions in a Binary Grid

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraph traversalBFS/DFSconnected components

Last updated

Tests iterative 2D graph traversal to count connected components of land cells without modifying the input or risking recursion stack overflow.

Problem Statement

You are given an m x n binary grid map_grid made up of 1s (land) and 0s (water). Two land cells are part of the same region if they are directly adjacent horizontally or vertically. Your task is to count and return the total number of distinct land regions in the grid.

Two important rules govern your implementation:

  • Read-only input. The grid must be in exactly the same state when your function returns as it was when it was called. Overwriting cells to track visited positions is not allowed.
  • No deep recursion. On very large grids a recursive flood fill can exhaust Python's call stack. Your solution must use an iterative traversal instead.

Constraints

  • m == len(map_grid)
  • n == len(map_grid[i])
  • 1 <= m, n <= 1000
  • map_grid[i][j] is either 0 or 1 (integer)
  • The grid must be unchanged after your function returns

Examples

Example 1

Input: count_land_regions([[1, 1, 0], [1, 0, 0], [0, 0, 1]])

Output: 2

Example 2

Input: count_land_regions([[1, 1, 1], [0, 0, 0], [1, 1, 1]])

Output: 2

Hints

Hint 1

Think of every land cell as a node in a graph. Two nodes share an edge when they are direct horizontal or vertical neighbors. Counting land regions is the same problem as counting connected components in that graph.

Hint 2

Since you cannot mark visited cells by writing into the grid, keep a separate flat bytearray of size m * n. Representing each cell as a single integer index (row * cols + col) lets you use cheap integer arithmetic instead of allocating coordinate tuples.

Hint 3

Replace the recursive flood fill with an explicit stack (or queue). Push a cell's flat index when you first mark it visited, then pop and expand its up to four neighbors. This keeps the call stack flat regardless of how large or oddly shaped a region is.