KatInterview

Count Separated Land Regions in a Binary Matrix

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraph-traversalbfsdfs

Last updated

Tests graph traversal skills by identifying connected components in a 2D grid using BFS or DFS.

You are given a rectangular matrix of size m × n where each cell contains either the character '1' (representing land) or '0' (representing water).

A land region is a maximal set of land cells where any two cells in the set can reach each other by moving through adjacent land cells. Two cells are adjacent if they share an edge (horizontal or vertical neighbors only; diagonal does not count). The matrix boundaries are treated as water.

Return the total number of distinct land regions in the matrix.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is either '0' or '1'

Examples

Example 1

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

Output: 2

Example 2

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

Output: 1

Hints

Hint 1

Think of the matrix as a graph where each land cell is a node. What kind of graph problem does counting regions become?

Hint 2

Use BFS or DFS starting from each unvisited land cell to explore an entire region at once.

Hint 3

Mark cells as visited when you add them to your queue or stack, not when you process them, to avoid adding the same cell multiple times.