Skip to content

Commit f377ac3

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

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

490-the-maze.js

+41
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,44 @@ function isValid(maze, row, col) {
138138
maze[row][col] !== 1
139139
)
140140
}
141+
142+
// another
143+
144+
/**
145+
* @param {number[][]} maze
146+
* @param {number[]} start
147+
* @param {number[]} destination
148+
* @return {boolean}
149+
*/
150+
const hasPath = function(maze, start, destination) {
151+
const m = maze.length, n = maze[0].length
152+
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
153+
const visited = new Set()
154+
let res = false
155+
dfs(start[0], start[1])
156+
return res
157+
158+
function dfs(i, j) {
159+
if(i < 0 || i >= m || j < 0 || j >= n || maze[i][j] === 1 || visited.has(`${i},${j}`)) return
160+
if(i === destination[0] && j === destination[1]) {
161+
res = true
162+
return
163+
}
164+
visited.add(`${i},${j}`)
165+
const ib = i, jb = j
166+
for(const [dx, dy] of dirs) {
167+
let ii = i, jj = j
168+
while(
169+
ii + dx >= 0 &&
170+
ii + dx < m &&
171+
jj + dy >= 0 &&
172+
jj + dy < n &&
173+
maze[ii + dx][jj + dy] === 0
174+
) {
175+
ii += dx
176+
jj += dy
177+
}
178+
dfs(ii, jj)
179+
}
180+
}
181+
};

0 commit comments

Comments
 (0)