You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.

Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

&nbsp;
Example 1:

Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
Output: 1
Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.


Example 2:

Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
Output: 2
Explanation: There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.


Example 3:

Input: maze = [[".","+"]], entrance = [0,0]
Output: -1
Explanation: There are no exits in this maze.


&nbsp;
Constraints:


	maze.length == m
	maze[i].length == n
	1 &lt;= m, n &lt;= 100
	maze[i][j] is either '.' or '+'.
	entrance.length == 2
	0 &lt;= entrancerow &lt; m
	0 &lt;= entrancecol &lt; n
	entrance will always be an empty cell.


class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        x, y = entrance
        m, n, infi = len(maze), len(maze[0]), int(1e5)
        reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)
        @lru_cache(None)
        def dfs(i, j):
            if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':
                return infi
            if reached(i, j):
                return 0
            maze[i][j] = '+'
            ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))
            maze[i][j] = '.'
            return ans
        ans = dfs(x, y)
        return -1 if ans>=infi else ans
class Solution {
    public int nearestExit(char[][] maze, int[] entrance) {
        int rows = maze.length, cols = maze[0].length, queueSize;
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[rows][cols];
        int[] curr;
        int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};
        int x, y, steps = 0;

        queue.offer(entrance);
        visited[entrance[0]][entrance[1]] = true;

        while (!queue.isEmpty()) {
            queueSize = queue.size();
            steps++;

            for (int i=0;i<queueSize;i++) {
                curr = queue.poll();

                for (int[] dir: dirs) {
                    x = dir[0]+curr[0];
                    y = dir[1]+curr[1];

                    if (x<0||x>=rows||y<0||y>=cols) continue;
                    if (visited[x][y] || maze[x][y] == '+') continue;

                    // check if we have reached boundary
                    if (x==0||x==rows-1||y==0||y==cols-1) return steps;

                    queue.offer(new int[]{x, y});
                    visited[x][y] = true;
                }
            }
        }

        return -1;
    }
}
class Solution {
public:
    //checks if the coordinates of the cell are that of an unvisited valid empty cell
    bool isValid(int x,int y,int n,int m, vector<vector<char>>& maze,vector<vector<int>>& visited){
        if(x>=0 && x<n && y>=0 && y< m && maze[x][y]!='+' && visited[x][y]!=1){
            return true;
        }
        return false;
    }

    //checks if the cell is a valid exit point
    bool isExit(int x,int y,int startX,int startY, vector<vector<char>>& maze,vector<vector<int>>& visited){
        if(x==startX && y==startY) return false;
        if( (x==0 || x==maze.size()-1 || y==0 || y==maze[0].size()-1)
           && maze[x][y]!='+')
        {
            return true;
        }
        return false;
    }

    //main BFS function
    int bfsHelper(vector<vector<char>>& maze,vector<vector<int>>& visited,int startX,int startY){
        queue<vector<int>>Queue;
        Queue.push({startX,startY,0});
        while(!Queue.empty()){
            int x = Queue.front()[0];
            int y = Queue.front()[1];
            int steps = Queue.front()[2];
            Queue.pop();
            //if you reach a valid exit, return the number of steps
            if(isExit(x,y,startX,startY,maze,visited)) return steps;
            int dx[4] = {0,-1,0,1};
            int dy[4] = {-1,0,1,0};
            //check in the 4 directions that you can travel
            for(int i=0;i<4;i++){
                int newX = x+dx[i] , newY = y+dy[i];
                //if the coordinates of the cell are that of
                //an unvisited valid empty cell, add it to the queue
                //and mark it as visited.
                if(isValid(newX,newY,maze.size(),maze[0].size(),maze,visited)){
                    Queue.push({newX,newY,steps+1});
                    visited[newX][newY] = 1;
                }
            }
        }
        //if you could not find a valid exit point, return -1
        return -1;
    }

    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        int n = maze.size();
        int m = maze[0].size();
        //create a 2d matrix and mark all the cells as -1,
        //denoting that they have not been visited yet.
        vector<vector<int>>visited(n,vector<int>(m,-1));
        return bfsHelper(maze,visited,entrance[0],entrance[1]);
    }
};
function nearestExit(maze, entrance) {
  const queue = []; // queue for bfs
  const empty = ".";
  const [height, width] = [maze.length, maze[0].length];
  const tried = [...Array(height)].map(() => Array(width).fill(false));
  const tryStep = (steps, row, col) => {
    // don't reuse once it's already been tried
    if (tried[row][col]) return;
    tried[row][col] = true;
    if (maze[row][col] !== empty) return; // blocked? i.e. can't step
    queue.push([steps, row, col]);
  };
  const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };
  const trySteppableDirs = (steps, row, col) => {
    // try steppable directions
    if (col < edges.right) tryStep(steps, row, col + 1);
    if (row < edges.bottom) tryStep(steps, row + 1, col);
    if (col > edges.left) tryStep(steps, row, col - 1);
    if (row > edges.top) tryStep(steps, row - 1, col);
  };
  let steps = 1, [row, col] = entrance;
  tried[row][col] = true; // don't reuse the entrance
  trySteppableDirs(steps, row, col);
  while (queue.length > 0) { // bfs
    [steps, row, col] = queue.shift();
    // path to the edge found?
    if (col === edges.left || col === edges.right) return steps;
    if (row === edges.top || row === edges.bottom) return steps;
    trySteppableDirs(steps + 1, row, col);
  }
  // NO path to the edge found
  return -1;
}
Nearest Exit from Entrance in Maze