Problem · Array
Query Whether an Island Size Exists
Learn this problemProblem statement
You are given a rectangular binary matrix grid and an integer array queries. A cell containing 1 is land and a cell containing 0 is water. Two land cells belong to the same island when they are connected through shared edges; diagonal contact does not connect islands.
Precompute the size of every island once. For each queries[i], return whether at least one island has exactly that many cells. Return the answers in query order.
Function
islandSizeExists(grid: int[][], queries: int[]) → boolean[]Examples
Example 1
grid = [[1,1,0,0],[0,1,0,1],[1,0,0,1]]queries = [1,2,3,4]return = [true,true,true,false]The island sizes are 3, 2, and 1.
Example 2
grid = [[1,0],[0,1]]queries = [1,2]return = [true,false]Diagonal land cells form two separate islands of size 1.
Example 3
grid = [[0,0],[0,0]]queries = [0,1]return = [false,false]There are no islands; size 0 is not an island size.
Constraints
gridis rectangular and may be empty.- Every grid cell is either
0or1. - Every query is an integer.
- The same precomputed set of sizes is used for every query.