Largest Connected Land Region
Trees & GraphsAuto-graded · 20 test casesLast 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 ≤ 10000 ≤ cols ≤ 1000- Each cell is either
0or1 - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the grid as an undirected graph where each land cell is a vertex and edges connect land cells that share a horizontal or vertical boundary. Each connected region is a connected component in this graph, and its size equals the number of vertices it contains.
The algorithm scans every cell in the grid. When it encounters a land cell that has not yet been visited, it launches a depth-first search to explore the entire region starting from that cell. During the search, it counts how many cells belong to the region. After exploring each region, it updates the maximum size seen so far.
An explicit stack is used for the DFS to avoid Python's recursion depth limit, which can be exceeded on large grids with long snake-shaped regions. A separate boolean matrix tracks which cells have been visited to ensure each cell is counted exactly once.
Why It Works
Each DFS explores exactly one connected component. From any starting cell, the search follows edges only to adjacent land cells, so it remains within the component. Conversely, every cell in the component is reachable from the starting cell via a path of adjacent land cells, and the DFS expands to all unvisited land neighbors, so every cell in the component is eventually visited.
Cells are marked visited when added to the stack, not when removed, ensuring no cell is added more than once. Since each removal increments the count by one, each cell contributes exactly one to the region size.
After a region is fully explored, all its cells are marked visited, so the outer scan will not start another search from any of them. Every region contains at least one cell, so the scan will discover every region exactly once. The maximum over all region sizes is therefore the answer.
Complexity
Time: O(R × C), where R is the number of rows and C is the number of columns. Each cell is examined once in the outer loop. Each land cell is pushed and popped from the stack exactly once, and each pop checks four neighbors in constant time.
Space: O(R × C) for the visited matrix. In the worst case (a grid entirely filled with land), the stack can also grow to O(R × C) cells. The solution does not mutate the input grid, preserving the original data.
Solution Code
from typing import List
def largest_land_region(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
best = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
seen[r][c] = True
stack = [(r, c)]
area = 0
while stack:
cr, cc = stack.pop()
area += 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] == 1 and not seen[nr][nc]):
seen[nr][nc] = True
stack.append((nr, nc))
best = max(best, area)
return best