Easy to Understand JS Solution | Detailed Explanation | BFS
Intuition\nMaybe it\'s all the practice solving graph related problems but when I read this one, I immediately thought BFS from the starting point to the border
# Intuition\nMaybe it\'s all the practice solving graph related problems but when I read this one, I immediately thought BFS from the starting point to the border of the grid.\n\n# Approach\nStarting at `entrance`. I performed BFS until a reached the border of the maze.  `getNeighbors` is a helper method for returning neighboring empty cells to whichever `row/col` combination.  `isExit` is a helper method for determining whether I\'m at the edge of the maze or not (excluding `entrance` if it happens to start on the border of the maze).\n\nI would have created corresponding 2D array called `visited` to keep track of the nodes I\'ve visited during the BFS traversal but to save space I just reused `maze`.  Visited positions were marked with a `1`.\n\nI hope this explanation is clear and helps someone. :)\n\n# Complexity\n- Time complexity:\nO(V + E)\n\n- Space complexity:\nO(V)\n\n# Code\n```\nlet nearestExit = (maze, entrance) => {\n  const EMPTY = ".", WALL = "+";\n  let getNeighbors = (row,col) => {\n    let neighbors = [];\n    let shifts = [[0,1],[0,-1],[1,0],[-1,0]];\n    let inBounds = (row, col) => row >= 0 && row < maze.length && col >= 0 && col < maze[0].length;\n    for (let [rShift,cShift] of shifts) {\n      let [nRow,nCol] = [row + rShift, col + cShift];\n      if (inBounds(nRow,nCol) && maze[nRow][nCol] !== WALL) neighbors.push([nRow,nCol]);\n    }\n    return neighbors;\n  }\n\n  let isExit = (row,col) => {\n    let atBorder = (row === 0 || col === 0 || row === maze.length - 1 || col === maze[0].length - 1);\n    let notEntrance = !(row === entrance[0] && col === entrance[1]);\n    return atBorder && notEntrance;\n  }\n\n  let count = 0;\n  let queue = [entrance];\n  maze[entrance[0]][entrance[1]] = 1;\n  while (queue.length) {\n    let length = queue.length;\n\n    for (let i = 0; i < length; i++) {\n      let [row,col] = queue.shift();\n      if (isExit(row,col)) return count;\n  \n      let neighbors = getNeighbors(row,col);\n      for (let [nRow, nCol] of neighbors) {\n        if (maze[nRow][nCol] === EMPTY) {\n          maze[nRow][nCol] = 1;\n          queue.push([nRow,nCol]);\n        }\n      }\n    }\n    count++;\n  }\n  return -1;\n}\n```
['Breadth-First Search', 'JavaScript']