[LeetCode] Maximum Number of Points From Grid Queries

2503. 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 queres[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
vector<int> maxPoints(vector<vector<int>>& A, vector<int>& queries) {
int n = A.size(), m = A[0].size();
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
unordered_map<int, int> score;
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> q;
q.push({A[0][0],0,0});
score[A[0][0]+1] += 1;
vector<vector<int>> vis(n,vector<int>(m,0));
vis[0][0] = true;
int ma = 0;
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) ma = max(ma, A[i][j]);
for(int i = A[0][0] + 1; i <= ma + 1;) {
while(q.size() and q.top()[0] < i) {
auto [_,y,x] = q.top(); q.pop();
for(int j = 0; j < 4; j++) {
int ny = y + dy[j], nx = x + dx[j];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx]) {
int num = A[ny][nx];
if(num < i) {
q.push({num,ny,nx});
score[i] += 1;
vis[ny][nx] = true;
} else {
q.push({num,ny,nx});
score[num + 1] += 1;
vis[ny][nx] = true;
}
}
}
}
if(q.size()) i = q.top()[0] + 1;
else i = ma + 2;
}
vector<pair<int,int>> S;
for(auto& [k,v] : score) S.push_back({k,v});
sort(begin(S), end(S));
for(int i = 1; i < S.size(); i++) S[i].second += S[i-1].second;
vector<int> res;
for(auto& q : queries) {
int now = min(q,ma + 1);
auto ub = upper_bound(begin(S), end(S), make_pair(now, INT_MAX));
if(ub == begin(S)) res.push_back(0);
else {
auto p = prev(ub);
res.push_back(p->second);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/maximum-number-of-points-from-grid-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.