> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Maximum Number of Points From Grid Queries

> Tested Python solution for LeetCode 2503 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 2503, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [Breadth-First Search](/catalog/topics/breadth-first-search), [Union-Find](/catalog/topics/union-find), [Sorting](/catalog/topics/sorting), [Heap (Priority Queue)](/catalog/topics/heap-priority-queue), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/description/).

Generate this problem as a practice environment: tested reference solution, 19 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2503   # by problem number
lcpy gen -s maximum_number_of_points_from_grid_queries   # by problem name
```

## Problem

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 all `4` directions: 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`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2025/03/15/image1.png)

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

```
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.length`
* `n == grid[i].length`
* `2 <= m, n <= 10^3`
* `4 <= m * n <= 10^5`
* `k == queries.length`
* `1 <= k <= 10^4`
* `1 <= grid[i][j], queries[i] <= 10^6`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_number_of_points_from_grid_queries/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_number_of_points_from_grid_queries/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq


class Solution:
    # Time: O(m*n*log(m*n) + k*log k)
    # Space: O(m*n)
    def max_points(self, grid: list[list[int]], queries: list[int]) -> list[int]:
        rows, cols = len(grid), len(grid[0])
        visited = [[False] * cols for _ in range(rows)]
        visited[0][0] = True
        heap: list[tuple[int, int, int]] = [(grid[0][0], 0, 0)]
        count = 0
        counts: dict[int, int] = {}
        for query in sorted(set(queries)):
            while heap and heap[0][0] < query:
                _, i, j = heapq.heappop(heap)
                count += 1
                for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                    if 0 <= ni < rows and 0 <= nj < cols and not visited[ni][nj]:
                        visited[ni][nj] = True
                        heapq.heappush(heap, (grid[ni][nj], ni, nj))
            counts[query] = count
        return [counts[query] for query in queries]
```

## Complexity

| Time | Space |
| - | - |
| O(m*n*log(m*n) + k*log k) | O(m\*n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.