Maximum Number of Points From Grid Queries Problem
Description
LeetCode Problem 2503.
You are given an m x n integer matrix grid and an array queries of size k.
Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process:
- If
queries[i]is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all4directions: up, down, left, and right. - Otherwise, you do not get any points, and you end this process.
After the process, answer[i] is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times.
Return the resulting array answer.
Example 1:

Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]
Output: [5,8,1]
Explanation: The diagrams above show which cells we visit to get points for each query.
Example 2:

Input: grid = [[5,2,1],[1,1,2]], queries = [3]
Output: [0]
Explanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.
Constraints:
m == grid.lengthn == grid[i].length2 <= m, n <= 10004 <= m * n <= 10^5k == queries.length1 <= k <= 10^41 <= grid[i][j], queries[i] <= 10^6
Solution
Approach: Offline queries with a min-heap
Queries do not affect each other, so answer them in increasing order of value and reuse the work. Keep a min-heap of the frontier cells, starting with the top-left cell, and a visited grid. For a query v, while the cheapest frontier cell has value less than v, pop it, count it as a collected point and push its unvisited neighbours. The count after this loop is the answer for v; larger queries simply continue from the same state. Store each answer at the query's original index.
Complexity: time O(k log k + mn log(mn)); space O(mn).
from heapq import heappop, heappush
class Solution:
def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:
m, n = len(grid), len(grid[0])
qs = sorted((v, i) for i, v in enumerate(queries))
ans = [0] * len(qs)
q = [(grid[0][0], 0, 0)]
cnt = 0
vis = [[False] * n for _ in range(m)]
vis[0][0] = True
for v, k in qs:
while q and q[0][0] < v:
_, i, j = heappop(q)
cnt += 1
for a, b in ((-1, 0), (0, 1), (1, 0), (0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and not vis[x][y]:
heappush(q, (grid[x][y], x, y))
vis[x][y] = True
ans[k] = cnt
return ans