|
| 1 | +/** |
| 2 | + * Title: Minimum Time to Visit a Cell in a Grid |
| 3 | + * Description: You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col]. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 04/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number[][]} grid |
| 10 | + * @return {number} |
| 11 | + */ |
| 12 | +var minimumTime = function (grid) { |
| 13 | + if (grid[0][1] > 1 && grid[1][0] > 1) { |
| 14 | + return -1; |
| 15 | + } |
| 16 | + const dp = new Array(grid.length) |
| 17 | + .fill() |
| 18 | + .map((_) => new Array(grid[0].length).fill()); |
| 19 | + const dir = [1, 0, -1, 0, 1]; |
| 20 | + const pq = new MinPriorityQueue({ |
| 21 | + compare: (a, b) => a[0] - b[0], |
| 22 | + }); |
| 23 | + pq.enqueue([0, 0, 0]); |
| 24 | + while (pq.size() > 0) { |
| 25 | + // Pick the node with the min potential value of time to visit |
| 26 | + const [val, i, j] = pq.dequeue(); |
| 27 | + if (dp[i][j] != null) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + dp[i][j] = val; |
| 31 | + if (i === grid.length - 1 && j === grid[0].length - 1) { |
| 32 | + break; |
| 33 | + } |
| 34 | + for (let k = 0; k < 4; ++k) { |
| 35 | + const [ni, nj] = [i + dir[k], j + dir[k + 1]]; |
| 36 | + if ( |
| 37 | + ni >= 0 && |
| 38 | + nj >= 0 && |
| 39 | + ni < grid.length && |
| 40 | + nj < grid[0].length && |
| 41 | + dp[ni][nj] == null |
| 42 | + ) { |
| 43 | + // 1 + dp[i][j]: Move 1 step from [i, j] to [ni, nj]; |
| 44 | + // grid[ni][nj] + (grid[ni][nj] & 1 ^ (ni+nj) & 1): After some back and forth in [i, j], finally reach the time |
| 45 | + // of grid[ni][nj], depending on its value and position, we may need to add 1 to it. |
| 46 | + const pVal = Math.max( |
| 47 | + 1 + dp[i][j], |
| 48 | + grid[ni][nj] + ((grid[ni][nj] & 1) ^ ((ni + nj) & 1)) |
| 49 | + ); |
| 50 | + pq.enqueue([pVal, ni, nj]); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return dp[grid.length - 1][grid[0].length - 1]; |
| 55 | +}; |
0 commit comments