KatInterview

Largest Connected Land Region

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsgraphsdfsconnected-components

Last updated

Measures understanding of graph traversal on a grid to compute connected-component sizes using four-directional adjacency.

You are given a rectangular grid where each cell contains either 0 (water) or 1 (land). Your task is to find the size of the largest connected region of land cells.

Two land cells belong to the same region if they are adjacent horizontally or vertically (up, down, left, or right). Diagonal adjacency does not connect cells. The size of a region is the count of land cells it contains.

Return the size of the largest land region in the grid. If the grid contains no land or is empty, return 0.

Constraints

  • 0 ≤ rows ≤ 1000
  • 0 ≤ cols ≤ 1000
  • Each cell is either 0 or 1
  • The grid may be empty ([]) or contain empty rows

Examples

Example 1

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

Output: 3

Example 2

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

Output: 0

Example 3

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

Output: 4

Hints

Hint 1

Think of the grid as a graph where each land cell is a node and edges connect orthogonally adjacent land cells. What graph algorithm finds all nodes in a connected component?

Hint 2

When you encounter an unvisited land cell, use depth-first search or breadth-first search to explore the entire region it belongs to, counting cells as you go.

Hint 3

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