KatInterview

Counting Separate Land Patches in a 0/1 Grid

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraphbfsconnected-components

Last updated

Count connected components of 1-cells in a binary grid using only up/down/left/right adjacency, via flood fill or union-find.

You are given a rectangular grid made up of 0s (water) and 1s (land). A patch is a maximal group of land cells in which any two cells are linked by a chain of land cells, where each step in the chain moves to a cell directly above, below, to the left of, or to the right of the previous one.

Cells that touch only at a corner are not linked.

Return the total number of patches in the grid.

Input

  • grid: a list of rows, each row a list of integers that are all 0 or 1. All rows have the same length.

Output

  • A single integer: the number of patches.

Special cases

  • If the grid has no rows, or its rows have no columns, return 0.
  • If the grid contains no land, return 0.

Constraints

  • Every entry of grid is 0 or 1.
  • All rows have equal length.
  • The grid may be empty ([] or [[]]), in which case the answer is 0.
  • Large grids (for example, 1000 x 1000 filled entirely with 1) are possible, so avoid unbounded recursion depth.
  • Do not rely on diagonal adjacency.

Examples

Example 1

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

Output: 3

Example 2

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

Output: 4

Example 3

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

Output: 1

Hints

Hint 1

Think of each land cell as a node, with edges between land cells that share a side. You are counting connected components.

Hint 2

Scan cells in row-major order. Whenever you meet a land cell you have not seen yet, you have found a new patch; then explore everything connected to it and mark it as seen.

Hint 3

Use an iterative traversal (a queue or an explicit stack) rather than deep recursion, and mark a cell as seen when you add it to the queue so it is never added twice.