Problem · Matrix

Count One Groups by Size

MediumAgodaCONTRACTOA

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

Examples
01 · 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
  • grid is a non-empty square matrix.
  • grid[i][j] is either 0 or 1.
  • queries.length >= 1
More Agoda problems
drafts saved locally
public int[] onesGroups(int[][] grid, int[] queries) {
  // write your code here
}
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]
expected[1,2,1,0]
sign in to submit