1
function nearestExit(maze, entrance) {2
const queue = []; // queue for bfs4
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 tried8
if (tried[row][col]) return;9
tried[row][col] = true;10
if (maze[row][col] !== empty) return; // blocked? i.e. can't step11
queue.push([steps, row, col]);13
const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };14
const trySteppableDirs = (steps, row, col) => {15
// try steppable directions16
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);22
[row, col] = entrance;23
tried[row][col] = true; // don't reuse the entrance24
trySteppableDirs(steps, row, col);25
while (queue.length > 0) {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);33
// NO path to the edge found