Problem · Matrix
Count One Groups by Size
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
gridis a non-empty square matrix.grid[i][j]is either0or1.queries.length >= 1
More Agoda problems
- Minimum Absolute Difference PairsONSITE INTERVIEW · Seen Jun 2026
- Minimum Price With Discount CouponsOA · Seen Jul 2025
- Lexicographically Smallest Task QueueOA · Seen Jul 2025
- Team FormationSeen Apr 2025
- Two-Core Process AssignmentSeen Apr 2025
- Unique Digits in RangeSeen Apr 2025
- Maximize Sum of Processed TimesSeen Sep 2024
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