|
| 1 | +/** |
| 2 | + * 3342. Find Minimum Time to Reach Last Room II |
| 3 | + * https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a dungeon with n x m rooms arranged as a grid. |
| 7 | + * |
| 8 | + * You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum |
| 9 | + * time in seconds when you can start moving to that room. You start from the room (0, 0) at |
| 10 | + * time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes one |
| 11 | + * second for one move and two seconds for the next, alternating between the two. |
| 12 | + * |
| 13 | + * Return the minimum time to reach the room (n - 1, m - 1). |
| 14 | + * |
| 15 | + * Two rooms are adjacent if they share a common wall, either horizontally or vertically. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} moveTime |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var minTimeToReach = function(moveTime) { |
| 23 | + const rows = moveTime.length; |
| 24 | + const cols = moveTime[0].length; |
| 25 | + const distances = Array.from({ length: rows }, () => new Array(cols).fill(Infinity)); |
| 26 | + const pq = new PriorityQueue((a, b) => a[0] - b[0]); |
| 27 | + pq.enqueue([0, 0, 0, 0]); |
| 28 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 29 | + |
| 30 | + distances[0][0] = 0; |
| 31 | + |
| 32 | + while (!pq.isEmpty()) { |
| 33 | + const [time, row, col, moveCount] = pq.dequeue(); |
| 34 | + |
| 35 | + if (row === rows - 1 && col === cols - 1) return time; |
| 36 | + |
| 37 | + if (time > distances[row][col]) continue; |
| 38 | + |
| 39 | + for (const [dr, dc] of directions) { |
| 40 | + const newRow = row + dr; |
| 41 | + const newCol = col + dc; |
| 42 | + |
| 43 | + if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue; |
| 44 | + |
| 45 | + const moveCost = moveCount % 2 === 0 ? 1 : 2; |
| 46 | + const startTime = Math.max(time, moveTime[newRow][newCol]); |
| 47 | + const newTime = startTime + moveCost; |
| 48 | + |
| 49 | + if (newTime < distances[newRow][newCol]) { |
| 50 | + distances[newRow][newCol] = newTime; |
| 51 | + pq.enqueue([newTime, newRow, newCol, moveCount + 1]); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return distances[rows - 1][cols - 1]; |
| 57 | +}; |
0 commit comments