Landmass Tally: Count Regions and Find the Biggest
Trees & GraphsAuto-graded · 18 test casesLast 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:
- the number of distinct landmasses, and
- 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
0or1. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of the grid as a graph: each land cell is a node, and two land cells are joined if they are directly above, below, left, or right of each other. A landmass is a connected component of this graph, so we need the number of components and the size of the biggest one.
Scan the grid cell by cell. When you find a land cell that has not been visited, it must belong to a landmass you have not seen yet. Increment the counter and run a traversal from that cell that visits every land cell reachable from it, counting them as you go. When the traversal ends, compare its cell count against the best size so far. A single traversal per landmass yields both answers.
The reference uses an iterative depth-first search with an explicit stack and a separate visited structure (one bytearray per row), so the input grid is left untouched.
Why it is correct
- Each landmass is counted once. A traversal marks every cell of its component. So the first time the scan reaches any cell of a landmass, nothing in it is marked yet and a new traversal starts. Every later cell of that landmass is already marked and is skipped.
- A traversal stays inside one landmass. It only steps to in-bounds, orthogonal neighbors that are land, and it reaches every such cell connected to the start.
- Each cell is counted once in the area. Cells are marked visited when pushed, not when popped, so a cell enters the stack at most once and the size counter increases once per pop.
- Diagonals are ignored because only four neighbor directions are examined.
- No land means no traversal ever starts, so the result is
[0, 0].
DFS versus BFS
Both give identical counts and sizes. DFS (stack) goes deep along one path before backtracking; BFS (queue) expands in layers of increasing distance. Swapping pop() for popleft() on a collections.deque converts the solution to BFS. Recursive DFS is risky because a single landmass can need a recursion depth on the order of 250,000, far beyond Python's default limit, so an explicit stack is used.
Complexity
- Time: O(R * C), since each cell is scanned once and each land cell is pushed and popped at most once with four neighbor checks.
- Space: O(R * C) for the visited flags plus up to O(R * C) for the stack in the worst case.
Reference solution
from typing import List
def landmass_stats(grid: List[List[int]]) -> List[int]:
rows = len(grid)
cols = len(grid[0]) if rows else 0
visited = [bytearray(cols) for _ in range(rows)]
count = 0
largest = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or visited[r][c]:
continue
count += 1
size = 0
stack = [(r, c)]
visited[r][c] = 1
while stack:
cr, cc = stack.pop()
size += 1
if cr > 0 and grid[cr - 1][cc] == 1 and not visited[cr - 1][cc]:
visited[cr - 1][cc] = 1
stack.append((cr - 1, cc))
if cr + 1 < rows and grid[cr + 1][cc] == 1 and not visited[cr + 1][cc]:
visited[cr + 1][cc] = 1
stack.append((cr + 1, cc))
if cc > 0 and grid[cr][cc - 1] == 1 and not visited[cr][cc - 1]:
visited[cr][cc - 1] = 1
stack.append((cr, cc - 1))
if cc + 1 < cols and grid[cr][cc + 1] == 1 and not visited[cr][cc + 1]:
visited[cr][cc + 1] = 1
stack.append((cr, cc + 1))
if size > largest:
largest = size
return [count, largest]