|
| 1 | +/** |
| 2 | + * 505. The Maze II |
| 3 | + * https://leetcode.com/problems/the-maze-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). |
| 7 | + * The ball can go through the empty spaces by rolling up, down, left or right, but it won't |
| 8 | + * stop rolling until hitting a wall. When the ball stops, it could choose the next direction. |
| 9 | + * |
| 10 | + * Given the m x n maze, the ball's start position and the destination, where |
| 11 | + * start = [startrow, startcol] and destination = [destinationrow, destinationcol], return |
| 12 | + * the shortest distance for the ball to stop at the destination. If the ball cannot stop |
| 13 | + * at destination, return -1. |
| 14 | + * |
| 15 | + * The distance is the number of empty spaces traveled by the ball from the start position |
| 16 | + * (excluded) to the destination (included). |
| 17 | + * |
| 18 | + * You may assume that the borders of the maze are all walls (see examples). |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[][]} maze |
| 23 | + * @param {number[]} start |
| 24 | + * @param {number[]} destination |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var shortestDistance = function(maze, start, destination) { |
| 28 | + const rows = maze.length; |
| 29 | + const cols = maze[0].length; |
| 30 | + const distances = new Array(rows).fill().map(() => new Array(cols).fill(Infinity)); |
| 31 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 32 | + const queue = [[start[0], start[1], 0]]; |
| 33 | + distances[start[0]][start[1]] = 0; |
| 34 | + |
| 35 | + while (queue.length) { |
| 36 | + const [row, col, distance] = queue.shift(); |
| 37 | + if (distance > distances[row][col]) continue; |
| 38 | + |
| 39 | + for (const [dx, dy] of directions) { |
| 40 | + let nextRow = row; |
| 41 | + let nextCol = col; |
| 42 | + let steps = 0; |
| 43 | + |
| 44 | + while (nextRow + dx >= 0 && nextRow + dx < rows && nextCol + dy >= 0 |
| 45 | + && nextCol + dy < cols && maze[nextRow + dx][nextCol + dy] === 0 |
| 46 | + ) { |
| 47 | + nextRow += dx; |
| 48 | + nextCol += dy; |
| 49 | + steps++; |
| 50 | + } |
| 51 | + |
| 52 | + const newDistance = distance + steps; |
| 53 | + if (newDistance < distances[nextRow][nextCol]) { |
| 54 | + distances[nextRow][nextCol] = newDistance; |
| 55 | + queue.push([nextRow, nextCol, newDistance]); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + const result = distances[destination[0]][destination[1]]; |
| 61 | + return result === Infinity ? -1 : result; |
| 62 | +}; |
0 commit comments