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
Companies: JPMorgan
Related Topics:
Array, Two Pointers, Breadth-First Search, Union Find, Sorting, Heap (Priority Queue), Matrix
Similar Questions:
Hints:
- The queries are all given to you beforehand so you can answer them in any order you want.
- Sort the queries knowing their original order to be able to build the answer array.
- Run a BFS on the graph and answer the queries in increasing order.
// OJ: https://leetcode.com/problems/maximum-number-of-points-from-grid-queries
// Author: github.com/lzl124631x
// Time: O(MNlogMN)
// Space: O(MN)
class Solution {
public:
vector<int> maxPoints(vector<vector<int>>& A, vector<int>& Q) {
int M = A.size(), N = A[0].size(), seen = 0, dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
vector<int> id(Q.size()), ans(Q.size());
iota(begin(id), end(id), 0);
sort(begin(id), end(id), [&](int a, int b) { return Q[a] < Q[b]; });
typedef array<int, 3> Node;
A[0][0] = -A[0][0];
priority_queue<Node> pq;
pq.push({A[0][0], 0, 0});
for (int i = 0; i < Q.size(); ++i) {
int q = Q[id[i]];
while (pq.size()) {
auto [val, x, y] = pq.top();
if (-val >= q) break;
pq.pop();
++seen;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || a >= M || b < 0 || b >= N || A[a][b] < 0) continue;
A[a][b] = -A[a][b];
pq.push({A[a][b], a, b});
}
}
ans[id[i]] = seen;
}
return ans;
}
};