KatInterview

Grid Land Mass Valuation

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsbreadth-first-searchdepth-first-search

Last 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.