Grid Land Mass Valuation
Trees & GraphsAuto-graded · 19 test casesLast updated
Find all orthogonal connected components of non-zero cells in a 2D grid and calculate the total sum of cell values for each component.
You are given a 2D rectangular grid representing a terrain map where each cell contains a non-negative integer indicating its resource value.
A contiguous land mass (or region) is formed by cells with non-zero values that are connected orthogonally (up, down, left, right). Diagonal connectivity does not count toward forming a single region.
Calculate the total resource value for every distinct land mass present on the map. The resource value of a land mass is the sum of all cell values belonging to that connected component.
Write a function get_region_scores that returns a list containing the total score for each distinct region. The regions in the output list should appear in the order that their first cell is discovered when scanning the grid row by row from top to bottom, and left to right within each row.
Constraints
- $N$ (number of rows) and $M$ (number of columns) are between $1$ and $200$.
board[i][j]is an integer between $0$ and $1000$.
Examples
Example 1
Input: get_region_scores([[1, 1, 0], [0, 0, 0], [0, 2, 2]])
Output: [2, 4]
Example 2
Input: get_region_scores([[0, 5], [5, 0]])
Output: [5, 5]
Example 3
Input: get_region_scores([[1, 2], [3, 4]])
Output: [10]
Hints
Hint 1
This problem can be modeled as finding connected components in an undirected graph.
Hint 2
Traverse the grid cell by cell. When an unvisited cell with a non-zero value is encountered, initiate a breadth-first search (BFS) or depth-first search (DFS).
Hint 3
To prevent deep recursion stack overflows in Python when exploring large connected components, prefer an iterative BFS or explicit stack-based DFS.
Hint 4
Mark cells as visited immediately upon adding them to the search queue/stack to avoid double counting and redundant work.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem can be solved by identifying connected components in an undirected graph representation of the grid.
- Each non-zero cell acts as a graph node.
- Edges exist between orthogonally adjacent (up, down, left, right) non-zero cells.
- Zero cells act as impassable boundaries.
We scan the grid in row-major order (top to bottom, left to right). When an unvisited non-zero cell is found:
- It marks the discovery of a new region.
- We perform an iterative Graph Traversal (Breadth-First Search using a queue or Depth-First Search using an explicit stack) starting from this cell.
- During the traversal, we accumulate the values of all reachable cells in this component and mark each cell as visited.
- Once the component is fully explored, we append the cumulative sum to our results.
Correctness & Implementation Details
- Iterative vs. Recursive Traversal: With grid dimensions up to $200 \times 200$, a single region could contain up to $40,000$ cells. A recursive DFS could trigger Python's default recursion limit (approx. 1,000). An iterative stack/queue avoids stack overflow issues.
- Visited Tracking: Marking a cell as visited at the moment it is pushed to the stack/queue ensures that no cell is added multiple times by neighboring nodes. This avoids unnecessary memory growth and guarantees each value is added to the sum exactly once.
Complexity Analysis
- Time Complexity: $\mathcal{O}(R \times C)$, where $R$ is the number of rows and $C$ is the number of columns. Every cell is visited at most once by the outer loop and processed at most once during component traversals.
- Space Complexity: $\mathcal{O}(R \times C)$ to maintain the
visitedarray and the explicit stack/queue during component exploration.
Python Reference Solution
from typing import List
def get_region_scores(board: List[List[int]]) -> List[int]:
if not board or not board[0]:
return []
rows = len(board)
cols = len(board[0])
visited = [[False] * cols for _ in range(rows)]
scores = []
for r in range(rows):
for c in range(cols):
if board[r][c] == 0 or visited[r][c]:
continue
# Start iterative DFS for a newly discovered component
stack = [(r, c)]
visited[r][c] = True
total = 0
while stack:
cr, cc = stack.pop()
total += board[cr][cc]
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:
if board[nr][nc] != 0 and not visited[nr][nc]:
visited[nr][nc] = True
stack.append((nr, nc))
scores.append(total)
return scores