Problem · Matrix
Count One Groups by Size
Learn this problemProblem statement
In a square grid, two cells are connected if they share an edge and contain the same value. Sharing an edge means up, down, left, or right, but not diagonal.
Given a square integer grid grid and an array queries, consider only connected groups of cells whose value is 1. For each query value, return how many connected groups of 1s have size exactly equal to that query.
Return an array where the i-th element is the answer for queries[i].
Function
onesGroups(grid: int[][], queries: int[]) → int[]Examples
Example 1
grid = [[1,1,1,1,1,1],[1,1,0,0,0,0],[0,0,0,1,1,1],[0,0,0,1,1,1],[0,0,1,0,0,0],[1,0,0,0,0,0]]queries = [6,1,8,2]return = [1,2,1,0]The grid contains four connected groups of 1s: one group with 8 cells, one group with 6 cells, and two groups with 1 cell. Therefore the answers for [6,1,8,2] are [1,2,1,0].
Constraints
gridis a non-empty square matrix.grid[i][j]is either0or1.queries.length >= 1