KatInterview

Landmass Tally: Count Regions and Find the Biggest

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphdfsbfs

Last updated

Count 4-connected groups of land cells in a binary grid and report the area of the largest group, testing graph traversal with correct visited-state handling.

You are given a rectangular map stored as a grid of integers. A cell holding 1 is land and a cell holding 0 is water.

A landmass is a maximal set of land cells in which any two cells can be joined by a path that moves only one step up, down, left, or right between land cells. Cells that touch only at a corner are not connected.

Write a function that returns a list of two integers:

  1. the number of distinct landmasses, and
  2. the area (number of cells) of the largest landmass.

If the map contains no land at all, return [0, 0].

The function must not depend on modifying the input in any way that changes the result, and every land cell belongs to exactly one landmass and is counted once in that landmass's area.

Constraints

  • The grid is rectangular with between 1 and 500 rows and between 1 and 500 columns.
  • Each entry is either 0 or 1.
  • Only the four orthogonal neighbors count as adjacent; diagonals do not.
  • A single landmass can cover the entire grid (up to 250,000 cells), so choose a traversal that will not exhaust the call stack.
  • The return value is a list [landmass_count, largest_area].

Examples

Example 1

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

Output: [3, 3]

Example 2

Input: landmass_stats([[0, 0], [0, 0]])

Output: [0, 0]

Hints

Hint 1

Treat each land cell as a node and each pair of orthogonally adjacent land cells as an edge. You are counting connected components and measuring their sizes.

Hint 2

Scan the grid. Whenever you meet land that has not been visited, that starts a new landmass: increment the count and run one traversal from it, counting the cells it reaches.

Hint 3

Use an explicit stack or queue instead of recursion to be safe on a 500x500 all-land grid, and mark a cell visited at the moment you add it to the stack or queue so it is never counted twice.