Skip to content

Commit 0d044da

Browse files
committed
Add solution #490
1 parent 6ca92e6 commit 0d044da

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,7 @@
478478
487|[Max Consecutive Ones II](./solutions/0487-max-consecutive-ones-ii.js)|Medium|
479479
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
480480
489|[Robot Room Cleaner](./solutions/0489-robot-room-cleaner.js)|Hard|
481+
490|[The Maze](./solutions/0490-the-maze.js)|Medium|
481482
491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium|
482483
492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy|
483484
493|[Reverse Pairs](./solutions/0493-reverse-pairs.js)|Hard|

solutions/0490-the-maze.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)