KatInterview

Connected Land Regions on a Grid (8-Direction)

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraph traversalBFS/DFSflood fill

Last updated

Tests graph traversal skills by counting connected components in a character grid where land cells are neighbours in all eight directions including diagonals.

Connected Land Regions on a Grid

You have an m × n grid where every cell holds either '1' (land) or '0' (water). Two land cells belong to the same region if you can walk from one to the other through a chain of land cells, stepping in any of the eight compass directions — that is, horizontally, vertically, or diagonally adjacent.

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


Details

  • A single isolated land cell is its own region.
  • A diagonal step counts as a valid connection. A cell at (r, c) can reach up to eight neighbours: (r±1, c), (r, c±1), and (r±1, c±1).
  • Water cells ('0') are never part of any region and cannot be crossed.
  • An empty grid (no rows, or rows of length zero) contains zero regions.

Constraints

  • 0 ≤ m, n ≤ 300
  • Every cell is either '1' or '0'
  • Rows are not necessarily the same length as columns (the grid can be non-square)
  • You may not modify the input grid

Examples

Example 1

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

Output: 1

Example 2

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

Output: 1

Example 3

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

Output: 0

Hints

Hint 1

Think of each land cell as a node and each pair of adjacent (including diagonal) land cells as an edge. The answer is the number of connected components in that graph. How would you count connected components efficiently?

Hint 2

Each time your outer scan finds an unvisited land cell, you have discovered a new region. A flood-fill from that cell — iterative DFS with an explicit stack, or BFS with a deque — can mark every cell in the same region as visited before you continue scanning. What data structure will you use to track visited cells?

Hint 3

A subtle but important detail: mark a cell as visited the moment you add it to the stack or queue, not when you remove it. If you wait until pop/dequeue, the same cell can be added multiple times by up to eight different neighbours, bloating your stack and wasting work.