2503. Maximum Number of Points From Grid Queries - Detailed Explanation
Problem Statement
You are given an m × n integer matrix grid
and an integer array queries
of length k. Compute an answer array answer
of length k where, for each query value q = queries[i]
, you start at the top‑left cell (0,0)
and repeatedly:
- If
q
is strictly greater than the value of your current cell (sayv
), you earn 1 point (but only the first time you visit that cell), and you may move to any of its 4 neighbors (up/down/left/right). - Otherwise, you stop and cannot earn more points.
Return answer
, where answer[i]
is the maximum points you can collect for queries[i]
. You are allowed to revisit cells (but won’t gain points again), and each query is independent. citeturn0search1
Examples
Input
grid = [[1,2,3],
[2,5,7],
[3,5,1]]
queries = [5,6,2]
Output [5,8,1]
Explanation
- q=5: you can visit all cells with value<5 reachable from (0,0):
cells {1,2,2,3,3} → 5 points.
- q=6: you can also visit the two “5” cells → +2 = 7,
then stop before 7; but you can re‑enter 1 at bottom‑right? No new points.
Total = 8.
- q=2: you stop immediately at (0,0)? 1<2 so get 1 point, but neighbors {2,2} are not <2. → 1
Constraints
1 ≤ m, n ≤ 10^5
withm·n ≤ 10^5
1 ≤ grid[i][j], queries[i] ≤ 10^9
1 ≤ k ≤ 10^5
Hints
- A naive per‑query BFS/DFS is O(k·mn) and too slow.
- Sort your queries in ascending order, and process them incrementally so that you never revisit cells you’ve already “unlocked.”
- You can use either a priority‑queue BFS (min‑heap by cell value) or a union‑find on all cells sorted by value to maintain a growing region of accessible cells from (0,0).
Approach 1 – Priority‑Queue BFS Across Queries
Idea
Maintain a min‑heap of frontier cells sorted by their grid
value. As you raise your threshold (query value), you pop and “unlock” all cells whose value is less than that threshold. Each cell, the first time you unlock it, increments your point count and pushes its 4 neighbors onto the heap. Because queries are sorted, you only ever push each cell once.
Steps
- Pair each query with its index and sort:
Q = sorted([(queries[i], i) for i in range(k)])
- Initialize a boolean
visited[m][n] = {false}
, a min‑heapheap = [(grid[0][0],0,0)]
, andvisited[0][0]=false
(we mark when popped). Setcount = 0
. - For each
(threshold, qi)
inQ
(in increasing threshold):- While
heap
not empty andheap[0].value < threshold
:- Pop
(val, x, y)
. - If already
visited[x][y]
, continue. - Mark
visited[x][y]=true
,count++
. - For each neighbor
(nx,ny)
in 4 directions inside bounds and not yet visited, push(grid[nx][ny], nx, ny)
ontoheap
.
- Pop
- Set
answer[qi] = count
.
- While
- Return
answer
.
Complexity
- Sorting queries: O(k log k)
- Each cell pushed/popped at most once: O(mn log (mn))
- Total: O((mn + k) log (mn)).
Python Code
Java Code
Approach 2 – Union‑Find on Sorted Cells
Idea
Sort all cells by their value ascending. Also sort queries
ascending. Maintain a union‑find structure that gradually adds cells whose value is < current_threshold
, unioning each new cell with its already‑added neighbors. Track the size of the component containing the start cell (0,0)
. As you raise the threshold per query, the component grows, and its size is your point total.
Steps
- Flatten cells:
cells = [(grid[i][j], i, j) for all i,j] sort cells by value
- Sort queries as before into
Q
. - Initialize a DSU over
m*n
elements, anadded
boolean grid, andptr=0
. - For each
(threshold, qi)
inQ
:- While
ptr < m*n
andcells[ptr].value < threshold
:- Let
(x,y)
= cell coords; markadded[x][y]=true
. - For each neighbor already
added
,union((x,y), neighbor)
. ptr++
.
- Let
- If
added[0][0]
,ans[qi] = size(root(0,0))
; else0
.
- While
- Return
ans
.
Complexity
- Sorting cells + queries: O((mn + k) log (mn))
- DSU operations: O(mn α(mn))
- Total: O((mn + k) log (mn)).
Python Code
Java Code
Common Mistakes
- Using ≤ threshold instead of < (the problem requires strictly greater).
- Re‑running a fresh BFS/DFS for each query → TLE.
- Forgetting to mark cells as “visited”/“added” and thus double‑counting.
Edge Cases
(0,0)
itself ≥ threshold → answer = 0.m=n=1
and any threshold >grid[0][0]
→ answer = 1.- Very large
grid
values outside query ranges → correct handling by sorting.
Related Problems
GET YOUR FREE
Coding Questions Catalog