Katkat

Compute board-game score from regions

AirbnbSoftware Engineer · Onsite

Last updated

This problem tests your ability to identify connected components in a 2D grid using graph traversal (BFS/DFS) and aggregate properties associated with those components.

Problem Statement

You are given an n x n board represented as a 2D grid. Each cell contains an integer value representing the number of "crowns" found in that location. A "region" is defined as a group of adjacent (up, down, left, right) cells that all have a non-zero value.

Your task is to compute the score for each unique region on the board. The score of a region is defined as the total number of crowns within all cells belonging to that region.

Implement a function get_region_scores(board) that returns a list of integers representing the scores of all distinct regions found on the board.

Function Signature

def get_region_scores(board: List[List[int]]) -> List[int]:

Constraints

  • n is between 1 and 200.
  • board[i][j] is between 0 and 1000.

Examples

Example 1: Input:

[[1, 1, 0],
 [0, 0, 0],
 [0, 2, 2]]

Output: [2, 4] Explanation: There are two regions. One has two 1s (sum = 2), and the other has two 2s (sum = 4).

Example 2: Input:

[[0, 5],
 [5, 0]]

Output: [5, 5] Explanation: Even though the 5s are diagonal, they are not connected horizontally or vertically, so they form two separate regions.

Edge Cases

  • Empty board or board with all zeros (should return an empty list).
  • A board where all cells are non-zero (should return a single score equal to the sum of all cells).

Hints

Hint 1

You can treat the grid as a graph where each non-zero cell is a node, and edges exist between adjacent non-zero cells.

Hint 2

Use a nested loop to iterate through every cell, and when you encounter a non-zero cell that hasn't been visited, trigger a traversal (BFS or DFS) to find all connected cells.

Hint 3

Keep track of visited cells using a boolean matrix or by modifying the input board temporarily to mark visited cells.

Follow-up questions

  • How would you modify your solution if the problem defined connectivity to include diagonals as well?
  • What is the time and space complexity of your solution, and can you optimize the space complexity if you are allowed to modify the input board?
  • If the board were extremely sparse (mostly zeros), how would you change your approach to improve performance?