Skip to content

Commit 656f155

Browse files
authored
Update 490-the-maze.js
1 parent f377ac3 commit 656f155

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

490-the-maze.js

+34
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,37 @@ const hasPath = function(maze, start, destination) {
179179
}
180180
}
181181
};
182+
183+
// another
184+
185+
/**
186+
* @param {number[][]} maze
187+
* @param {number[]} start
188+
* @param {number[]} destination
189+
* @return {boolean}
190+
*/
191+
const hasPath = function(maze, start, destination) {
192+
const m = maze.length, n = maze[0].length
193+
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
194+
const visited = new Set()
195+
const q = [start]
196+
while(q.length) {
197+
const [i, j] = q.pop()
198+
if(i === destination[0] && j === destination[1]) return true
199+
visited.add(`${i},${j}`)
200+
for(const [dx, dy] of dirs) {
201+
let ni = i, nj = j
202+
while(valid(ni + dx, nj + dy)) {
203+
ni += dx
204+
nj += dy
205+
}
206+
if(!visited.has(`${ni},${nj}`)) q.push([ni, nj])
207+
}
208+
}
209+
210+
return false
211+
212+
function valid(i, j) {
213+
return i >= 0 && i < m && j >= 0 && j < n && maze[i][j] === 0
214+
}
215+
};

0 commit comments

Comments
 (0)