|
| 1 | +/** |
| 2 | + * 2503. Maximum Number of Points From Grid Queries |
| 3 | + * https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n integer matrix grid and an array queries of size k. |
| 7 | + * |
| 8 | + * Find an array answer of size k such that for each integer queries[i] you start in the top left |
| 9 | + * cell of the matrix and repeat the following process: |
| 10 | + * - If queries[i] is strictly greater than the value of the current cell that you are in, then |
| 11 | + * you get one point if it is your first time visiting this cell, and you can move to any adjacent |
| 12 | + * cell in all 4 directions: up, down, left, and right. |
| 13 | + * - Otherwise, you do not get any points, and you end this process. |
| 14 | + * |
| 15 | + * After the process, answer[i] is the maximum number of points you can get. Note that for each |
| 16 | + * query you are allowed to visit the same cell multiple times. |
| 17 | + * |
| 18 | + * Return the resulting array answer. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[][]} grid |
| 23 | + * @param {number[]} queries |
| 24 | + * @return {number[]} |
| 25 | + */ |
| 26 | +var maxPoints = function(grid, queries) { |
| 27 | + const rows = grid.length; |
| 28 | + const cols = grid[0].length; |
| 29 | + const result = new Array(queries.length); |
| 30 | + const sortedQueries = queries |
| 31 | + .map((value, index) => ({ value, index })) |
| 32 | + .sort((a, b) => a.value - b.value); |
| 33 | + const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]; |
| 34 | + const queue = new MinPriorityQueue(([row, col]) => grid[row][col]); |
| 35 | + const visited = new Set(); |
| 36 | + |
| 37 | + queue.enqueue([0, 0]); |
| 38 | + visited.add('0,0'); |
| 39 | + |
| 40 | + let queryIndex = 0; |
| 41 | + let points = 0; |
| 42 | + while (queue.size()) { |
| 43 | + const [row, col] = queue.dequeue(); |
| 44 | + const currentValue = grid[row][col]; |
| 45 | + while (queryIndex < sortedQueries.length && currentValue >= sortedQueries[queryIndex].value) { |
| 46 | + result[sortedQueries[queryIndex].index] = points; |
| 47 | + queryIndex++; |
| 48 | + } |
| 49 | + if (queryIndex === sortedQueries.length) break; |
| 50 | + points++; |
| 51 | + for (const [rowOffset, colOffset] of directions) { |
| 52 | + const nextRow = row + rowOffset; |
| 53 | + const nextCol = col + colOffset; |
| 54 | + const positionKey = `${nextRow},${nextCol}`; |
| 55 | + if (nextRow >= 0 && nextRow < rows && nextCol >= 0 && nextCol < cols |
| 56 | + && !visited.has(positionKey)) { |
| 57 | + visited.add(positionKey); |
| 58 | + queue.enqueue([nextRow, nextCol]); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + while (queryIndex < sortedQueries.length) { |
| 63 | + result[sortedQueries[queryIndex].index] = points; |
| 64 | + queryIndex++; |
| 65 | + } |
| 66 | + |
| 67 | + return result; |
| 68 | +}; |
0 commit comments