KatInterview

Count Separate Land Regions in a Grid

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraphsbfsdfs

Last updated

Tests flood-fill traversal to identify connected components in a 2D grid with four-directional adjacency.

You are given a 2D grid represented as a list of lists, where each cell contains either the character '1' (representing land) or '0' (representing water).

Your task is to determine how many separate land regions exist in the grid. A land region is formed by land cells that are connected through shared edges—specifically, cells are considered connected if they are adjacent horizontally or vertically (up, down, left, or right). Cells that touch only at their corners (diagonally) do not belong to the same region.

Write a function that returns the total count of distinct land regions.

Constraints:

  • The grid may be None, empty, or contain empty rows
  • 0 ≤ rows, cols ≤ 1000
  • Each cell is either the string '1' or '0'
  • Adjacency is defined as sharing an edge (4-directional connectivity only)
  • The input grid should not be modified

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

Example 2

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

Output: 2

Example 3

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

Output: 5

Hints

Hint 1

Think of the grid as a graph where land cells are nodes. What graph algorithm finds all connected components?

Hint 2

When you encounter an unvisited land cell, you've discovered a new region. How can you mark all cells in that region to avoid counting them again?

Hint 3

Consider using a queue-based traversal to explore each region. Mark cells as visited when you add them to the queue, not when you remove them.