|
| 1 | +/** |
| 2 | + * 1926. Nearest Exit from Entrance in Maze |
| 3 | + * https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and |
| 7 | + * walls (represented as '+'). You are also given the entrance of the maze, where entrance |
| 8 | + * = [entrancerow, entrancecol] denotes the row and column of the cell you are initially |
| 9 | + * standing at. |
| 10 | + * |
| 11 | + * In one step, you can move one cell up, down, left, or right. You cannot step into a cell |
| 12 | + * with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit |
| 13 | + * from the entrance. An exit is defined as an empty cell that is at the border of the maze. |
| 14 | + * The entrance does not count as an exit. |
| 15 | + * |
| 16 | + * Return the number of steps in the shortest path from the entrance to the nearest exit, |
| 17 | + * or -1 if no such path exists. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {character[][]} maze |
| 22 | + * @param {number[]} entrance |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var nearestExit = function(maze, entrance) { |
| 26 | + const queue = [[entrance, 0]]; |
| 27 | + |
| 28 | + while (queue.length) { |
| 29 | + const [cell, steps] = queue.shift(); |
| 30 | + const [i, j] = cell; |
| 31 | + if (i === maze.length || i === -1 || j === maze[0].length || j === -1 || maze[i][j] !== '.') { |
| 32 | + continue; |
| 33 | + } |
| 34 | + if ((i === maze.length - 1 || i === 0 || j === maze[0].length - 1 || j === 0) && steps !== 0) { |
| 35 | + return steps; |
| 36 | + } |
| 37 | + maze[i][j] = '*'; |
| 38 | + queue.push([[i, j + 1], steps + 1]); |
| 39 | + queue.push([[i, j - 1], steps + 1]); |
| 40 | + queue.push([[i + 1, j], steps + 1]); |
| 41 | + queue.push([[i - 1, j], steps + 1]); |
| 42 | + } |
| 43 | + |
| 44 | + return -1; |
| 45 | +}; |
0 commit comments