✅ Simple solution + Why bfs not dfs
IntuitionMy first intuition was that I need a graph traversal algorithm; maybe DFS or BFS. I used DFS at first, but I hit time limit, when I tried BFS, the solu
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
My first intuition was that I need a graph traversal algorithm; maybe DFS or BFS. I used DFS at first, but I hit time limit, when I tried BFS, the solution was accepted.

# But Why BFS Not DFS?
## Why DFS is bad?
DFS will rush deep down a single path until it hits a dead-end or finds a way out, however even this way out might not be the shortest path! and to make sure you find shortest path, you will need to traverse all other paths and compare solutions! which is so bad. Not only that, you will also have to add additional logic to make sure you are not moving in cycles (this is harder than simply checking if a cell is visited or not)
## Why BFS is good?
BFS is very careful. It will guarantee that the first solution it reaches is actually the shortest path because it takes one step forward in all possible solutions and then repeats, until it finds a way out, also it's easy to handle cycles by simply marking cells you visited to not visit them again.
# Approach
A simple queue + while loop can help us with this, handling each cell is made of 4 steps:
- ignore cell if it's invalid or visited already
- mark this cell to not visit it again
- if you reached border, return
- repeat the same on all neighbours.

Notes:
- The queue keeps track of nodes and steps so far, not just the nodes.
- We visit all neighbours without validating them, because we postpone the validation steps when we handle each one separately.. this makes the code simpler.
# Complexity
- Time complexity: O(m x n) 
- Space complexity: O(m x n) 

# Code
```javascript []
/**
 * @param {character[][]} maze
 * @param {number[]} entrance
 * @return {number}
 */
var nearestExit = function(maze, entrance) {
    let queue = []
    queue.push([entrance, 0])
    const m = maze.length
    const n = maze[0].length
    while(queue.length){
        const [cell, steps] = queue.shift()
        const [i,j] = cell
        // check if cell is invalid/visited 
        if(i===m || i===-1 || j===n || j===-1 || maze[i][j]!=='.'){
            continue
        }

        // mark cell as visited
        maze[i][j] = '*'

        // reached border
        if((i===m-1 || i===0 || j===n-1 || j===0) && steps!==0){ 
            return steps
        }
        
        // visit neighbours
        queue.push([[i,j+1], steps+1])
        queue.push([[i,j-1], steps+1])
        queue.push([[i+1,j], steps+1])
        queue.push([[i-1,j], steps+1])
    }
    return  -1
};



```
['Breadth-First Search', 'JavaScript']