Skip to content

Commit e66b72d

Browse files
committed
Time: 13 ms (99.6%), Space: 65.1 MB (89.47%) - LeetHub
source:9a54c8a0b7d71b8bb9b4b9fb7893a04536449656
1 parent db7ad09 commit e66b72d

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
var nearestExit = function(maze, entrance) {
2+
const rows = maze.length;
3+
const cols = maze[0].length;
4+
const dx = [0, 1, 0, -1];
5+
const dy = [1, 0, -1, 0];
6+
7+
const queue = [[entrance[0], entrance[1], 0]];
8+
maze[entrance[0]][entrance[1]] = "+";
9+
10+
while (queue.length > 0) {
11+
const [cx, cy, cnt] = queue.shift();
12+
13+
for (let i = 0; i < 4; i++) {
14+
const nx = cx + dx[i];
15+
const ny = cy + dy[i];
16+
17+
if (nx < 0 || nx >= rows || ny < 0 || ny >= cols || maze[nx][ny] === "+") continue;
18+
19+
if (nx === 0 || ny === 0 || nx === rows - 1 || ny === cols - 1) {
20+
return cnt + 1;
21+
}
22+
23+
maze[nx][ny] = "+";
24+
queue.push([nx, ny, cnt + 1]);
25+
}
26+
}
27+
return -1;
28+
};

0 commit comments

Comments
 (0)