|
| 1 | +/** |
| 2 | + * 490. The Maze |
| 3 | + * https://leetcode.com/problems/the-maze/ |
| 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], |
| 12 | + * return true if the ball can stop at the destination, otherwise return false. |
| 13 | + * |
| 14 | + * You may assume that the borders of the maze are all walls (see examples). |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} maze |
| 19 | + * @param {number[]} start |
| 20 | + * @param {number[]} destination |
| 21 | + * @return {boolean} |
| 22 | + */ |
| 23 | +var hasPath = function(maze, start, destination) { |
| 24 | + const rows = maze.length; |
| 25 | + const cols = maze[0].length; |
| 26 | + const visited = new Set(); |
| 27 | + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; |
| 28 | + |
| 29 | + return helper(start[0], start[1]); |
| 30 | + |
| 31 | + function helper(row, col) { |
| 32 | + if (visited.has(`${row},${col}`)) return false; |
| 33 | + visited.add(`${row},${col}`); |
| 34 | + |
| 35 | + if (row === destination[0] && col === destination[1]) return true; |
| 36 | + |
| 37 | + for (const [dr, dc] of directions) { |
| 38 | + let newRow = row; |
| 39 | + let newCol = col; |
| 40 | + |
| 41 | + while (newRow + dr >= 0 && newRow + dr < rows && newCol + dc >= 0 && newCol + dc < cols |
| 42 | + && maze[newRow + dr][newCol + dc] === 0) { |
| 43 | + newRow += dr; |
| 44 | + newCol += dc; |
| 45 | + } |
| 46 | + |
| 47 | + if (helper(newRow, newCol)) return true; |
| 48 | + } |
| 49 | + |
| 50 | + return false; |
| 51 | + } |
| 52 | +}; |
0 commit comments