2025-03-28 Daily Challenge
Today I have done leetcode's March LeetCoding Challenge with cpp
.
March LeetCoding Challenge 28
Description
Maximum Number of Points From Grid Queries
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 all4
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
.
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.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
k == queries.length
1 <= k <= 104
1 <= grid[i][j], queries[i] <= 106
Solution
class Solution {
const int MOVES[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
using pi = pair<int, int>;
using pii = pair<int, pi>;
public:
vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {
int len = queries.size();
int rows = grid.size();
int cols = grid.front().size();
vector<int> indice(len);
iota(indice.begin(), indice.end(), 0);
sort(indice.begin(), indice.end(), [&](int a, int b){ return queries[a] < queries[b]; });
priority_queue<pii, vector<pii>, greater<pii>> candidates;
int current = 0;
vector<int> answer(len);
vector<vector<bool>> added(rows, vector<bool>(cols));
candidates.push({grid[0][0], {0, 0}});
added[0][0] = true;
for(auto index : indice) {
int q = queries[index];
while(candidates.size() && q > candidates.top().first) {
auto [val, coordinates] = candidates.top();
candidates.pop();
auto [row, col] = coordinates;
current += 1;
for(int m = 0; m < 4; ++m) {
int newRow = row + MOVES[m][0];
int newCol = col + MOVES[m][1];
if(newRow < 0 || newCol < 0 || newRow >= rows || newCol >= cols) continue;
if(added[newRow][newCol]) continue;
added[newRow][newCol] = true;
candidates.push({grid[newRow][newCol], {newRow, newCol}});
}
}
answer[index] = current;
}
return answer;
}
};
// Accepted
// 21/21 cases passed (91 ms)
// Your runtime beats 75.36 % of cpp submissions
// Your memory usage beats 94.2 % of cpp submissions (39 MB)