KatInterview

Connected Land Regions in a Character Matrix

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsgraph-traversaldfsconnected-components

Last updated

Tests graph traversal and connected-component identification on a 2D grid using flood-fill techniques.

You receive an m × n matrix of characters in which every cell holds either '1' (representing land) or '0' (representing water). A region is a maximal set of land cells connected through horizontal or vertical adjacency; diagonal connections do not join cells into the same region. The perimeter of the matrix is treated as water.

Write a function that computes how many distinct land regions exist in the matrix.

Parameters

  • matrix: a 2D list of strings, where each string is '0' or '1'

Return Value

An integer representing the count of disconnected land regions.

Constraints

  • 1 ≤ m, n ≤ 300
  • Every cell is either '0' or '1'

Examples

Example 1

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

Output: 3

Hints

Hint 1

Model the matrix as a graph where each land cell is a vertex and edges connect orthogonally adjacent land cells. The answer is the number of connected components in this graph.

Hint 2

Iterate through every cell; when you encounter an unvisited land cell, you have discovered a new region. Use depth-first or breadth-first traversal to mark all cells in that region as visited.

Hint 3

Mark cells as visited when you add them to your traversal structure (stack or queue), not when you process them, to avoid redundant work and excessive memory usage.