|
| 1 | +/** |
| 2 | + * 1293. Shortest Path in a Grid with Obstacles Elimination |
| 3 | + * https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). |
| 7 | + * You can move up, down, left, or right from and to an empty cell in one step. |
| 8 | + * |
| 9 | + * Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right |
| 10 | + * corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to |
| 11 | + * find such walk return -1. |
| 12 | + */ |
| 13 | + |
| 14 | +function shortestPath(grid, k) { |
| 15 | + const rows = grid.length; |
| 16 | + const cols = grid[0].length; |
| 17 | + if (rows === 1 && cols === 1) return 0; |
| 18 | + |
| 19 | + let steps = 1; |
| 20 | + let queue = [[0, 0, k]]; |
| 21 | + const visited = Array.from({ length: rows }, () => new Int16Array(cols).fill(-1)); |
| 22 | + const directions = [0, -1, 0, 1, 0]; |
| 23 | + |
| 24 | + while (queue.length) { |
| 25 | + const nextLevel = []; |
| 26 | + for (const [row, col, obstaclesLeft] of queue) { |
| 27 | + for (let i = 0; i < 4; i++) { |
| 28 | + const newRow = row + directions[i]; |
| 29 | + const newCol = col + directions[i + 1]; |
| 30 | + |
| 31 | + if (newRow < 0 || newRow === rows || newCol < 0 |
| 32 | + || newCol === cols || visited[newRow][newCol] >= obstaclesLeft) continue; |
| 33 | + |
| 34 | + if (newRow === rows - 1 && newCol === cols - 1) return steps; |
| 35 | + |
| 36 | + const remainingObstacles = grid[newRow][newCol] ? obstaclesLeft - 1 : obstaclesLeft; |
| 37 | + visited[newRow][newCol] = remainingObstacles; |
| 38 | + nextLevel.push([newRow, newCol, remainingObstacles]); |
| 39 | + } |
| 40 | + } |
| 41 | + steps++; |
| 42 | + queue = nextLevel; |
| 43 | + } |
| 44 | + |
| 45 | + return -1; |
| 46 | +} |
0 commit comments