Nearest Exit from Entrance in Maze LeetCode solution in JavaScript

1
function nearestExit(maze, entrance) {
2
const queue = []; // queue for bfs
3
const empty = ".";
4
const [height, width] = [maze.length, maze[0].length];
5
const tried = [...Array(height)].map(() => Array(width).fill(false));
6
const tryStep = (steps, row, col) => {
7
// don't reuse once it's already been tried
8
if (tried[row][col]) return;
9
tried[row][col] = true;
10
if (maze[row][col] !== empty) return; // blocked? i.e. can't step
11
queue.push([steps, row, col]);
12
};
13
const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };
14
const trySteppableDirs = (steps, row, col) => {
15
// try steppable directions
16
if (col < edges.right) tryStep(steps, row, col + 1);
17
if (row < edges.bottom) tryStep(steps, row + 1, col);
18
if (col > edges.left) tryStep(steps, row, col - 1);
19
if (row > edges.top) tryStep(steps, row - 1, col);
20
};
21
let steps = 1,
22
[row, col] = entrance;
23
tried[row][col] = true; // don't reuse the entrance
24
trySteppableDirs(steps, row, col);
25
while (queue.length > 0) {
26
// bfs
27
[steps, row, col] = queue.shift();
28
// path to the edge found?
29
if (col === edges.left || col === edges.right) return steps;
30
if (row === edges.top || row === edges.bottom) return steps;
31
trySteppableDirs(steps + 1, row, col);
32
}
33
// NO path to the edge found
34
return -1;
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0