Maximum Number of Points From Grid Queries

Hard Topics Company Tags

For each value in queries, start at the top-left cell of grid. You may move up, down, left, or right through cells whose values are strictly smaller than that query value. You cannot pass through a cell whose value is greater than or equal to the query.

Earn one point for each distinct cell you can reach, including the starting cell if its value is small enough. Revisiting a cell earns no extra points. Each query is independent.

Return the maximum number of points for every query, in the original query order. If the starting cell is blocked for a query, its answer is 0.

The diagrams follow the queries in input order. Hatching marks cells reachable for each query.

Example 1:

Maximum Number of Points From Grid Queries, example 1: illustration of the example

Input: grid = [[1,4],[2,3]]
queries = [2,4,5]

Output: [1,3,4]

Explanation: For query 2, only the starting cell has a small enough value. For query 4, cells with values 1, 2, and 3 are connected, giving 3 points. Query 5 allows all four cells.

Example 2:

Maximum Number of Points From Grid Queries, example 2: illustration of the example

Input: grid = [[4,1],[1,1]]
queries = [4,5]

Output: [0,4]

Explanation: A cell equal to the query is blocked. Query 4 cannot enter the starting cell and earns 0 points; query 5 reaches all four cells.

Example 3:

Maximum Number of Points From Grid Queries, example 3: illustration of the example

Input: grid = [[1,9,1],[2,9,2]]
queries = [3,10,3]

Output: [2,6,2]

Explanation: For query 3, only the two cells in the leftmost column are reachable. The middle column blocks access to the smaller values on the right. Query 10 reaches all six cells; the repeated query 3 again earns 2 points.

Constraints:

  • 2 <= grid.length, grid[i].length <= 1000
  • The grid is rectangular and contains at most 100000 cells.
  • 1 <= queries.length <= 10000
  • 1 <= grid[i][j], queries[i] <= 1000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.