Given a 2D grid grid of characters where each character represents a terrain type, calculate the total score of the board game.
A connected region is a group of cells with the same terrain type that are connected horizontally or vertically (not diagonally). The score of a connected region of size k is k2, the square of its size.
Return the total score, which is the sum of the scores of all connected regions in the grid.
Function Signature
def board_game_score(grid: list[list[str]]) -> int:
Rules
-
grid
is a list of rows, and each row is a list of one-character strings. All rows have the same length.
-
Two cells are in the same region only when a path of edge-sharing cells with the same letter joins them. Cells with the same letter in separate regions are scored separately.
-
Every cell belongs to exactly one region, including a cell with no matching neighbor (a region of size 1).
Constraints
-
1 <= len(grid) <= 100
-
1 <= len(grid[0]) <= 100
-
grid[i][j]
is a lowercase English letter
Examples
Input: grid = [["a","a","b"],
["a","b","b"],
["b","b","a"]]
Output: 35
The a cells at (0,0), (0,1) and (1,0) form a region of size 3, the five b cells form one region of size 5, and the a at (2,2) touches only b cells, so it is a region of size 1. The scores are 9, 25 and 1, for a total of 35.
Input: grid = [["x","x"],
["x","x"]]
Output: 16
All four cells form one connected region of size 4, which scores 16.
Input: grid = [["a","b"],
["b","a"]]
Output: 4
Matching letters only touch diagonally, which does not connect them, so there are four regions of size 1 and each scores 1.