KatInterview

Count Land Cells in a Connected Region

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraph traversalDFSBFS

Last updated

Tests iterative graph traversal (DFS/BFS) on a binary grid, including bounds handling, visited-marking strategy, and complexity analysis.

Count Land Cells in a Connected Region

You are given an m x n binary grid where each cell holds either 0 (water) or 1 (land). Two land cells belong to the same region if you can travel between them using only up, down, left, and right steps — diagonal moves do not count.

Write a function count_region(grid, row, col) that returns the number of land cells in the region that contains the cell at position (row, col).

Return 0 if any of the following apply:

  • grid is empty.
  • (row, col) is outside the grid boundaries (including negative indices).
  • The cell at (row, col) is water.

You may modify the grid in place to track which cells have already been visited, or you may use a separate data structure — whichever you choose, be prepared to explain the trade-off.

Constraints

  • 0 <= m, n <= 1000 (grid may be empty)
  • Every cell value is 0 or 1
  • row and col may be any integer, including negative values
  • 4-directional connectivity only (up, down, left, right)
  • A single isolated land cell has a region size of 1
  • If the function is called twice on the same region and the grid is mutated, the second call returns 0

Examples

Example 1

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

Output: 3

Example 2

Input: count_region([[1, 1, 0], [0, 1, 0], [1, 0, 1]], 2, 0)

Output: 1

Example 3

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

Output: 0

Hints

Hint 1

Before indexing into the grid, explicitly check that row and col are both non-negative and within bounds — Python's negative indexing will silently wrap around and give you the wrong answer.

Hint 2

Mark each cell as visited the moment you push it onto the stack, not when you pop it. Marking on pop lets the same cell get pushed multiple times by different neighbors, which inflates the count.

Hint 3

Recursive DFS is elegant but risky here: a 1000×1000 all-land grid would require a million recursive calls, well past Python's default limit. An explicit stack on the heap gives you the same traversal order without that risk.