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:
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.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.lengthn == grid[i].length2 <= m, n <= 10004 <= m * n <= 105k == queries.length1 <= k <= 1041 <= grid[i][j], queries[i] <= 106class Solution {
private static final int[][] dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
private boolean isValid(int m, int n, int i, int j, boolean[][] vis){
return i>=0 && j>=0 && i<m && j<n && !vis[i][j];
}
// private UnionFind {
// int[] root;
// int[] size;
// UnionFind(int n){
// root = new int[n];
// size = new int[n];
// for(int i=0; i<n; i++){
// root[i] = i;
// size[i] = 1;
// }
// }
// int find(int node){
// if(node = root[node])
// return node;
// return find(root[node]);
// }
// int union(int x, int y){
// int rootX = find(x);
// int rootY = find(y);
// if (rootX != rootY){
// if (size[rootX] > size[rootY]){
// root[rootY] = rootX;
// size[rootX] += size[rootY];
// } else {
// root[rootX] = rootY;
// size[rootY] += size[rootX];
// }
// }
// }
// }
public int[] maxPoints(int[][] grid, int[] queries) {
Queue<int[]> bfs = new PriorityQueue<>((a, b) -> a[2] - b[2]);
TreeMap<Integer, Integer> bst = new TreeMap<>();
int m = grid.length, n = grid[0].length, q = queries.length, count = 0, maxSeen = 0;
boolean[][] vis = new boolean[m][n];
bfs.offer(new int[]{0, 0, grid[0][0]});
bst.put(0, 0);
while(!bfs.isEmpty()){
int[] top = bfs.poll();
if(vis[top[0]][top[1]])
continue;
vis[top[0]][top[1]] = true;
maxSeen = Math.max(maxSeen, top[2]);
bst.put(maxSeen+1, ++count);
for(int[] d: dirs){
int I = top[0] + d[0], J = top[1] + d[1];
if(isValid(m, n, I, J, vis))
bfs.offer(new int[]{I, J, grid[I][J]});
}
// System.out.println(bst + "\t" + grid[top[0]][top[1]]);
}
int[] answer = new int[q];
for(int i=0; i<q; i++)
answer[i] = bst.get(bst.containsKey(queries[i]) ? queries[i] : bst.lowerKey(queries[i]));
return answer;
}
}