Nearest Exit from Entrance in Maze — BFS

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

Given a maze grid of + (walls) and . (empty), find the minimum steps from entrance to any exit (border empty cell that is not the entrance).


Solutions

Python

from collections import deque
class Solution:
    def nearestExit(self, maze: list[list[str]], entrance: list[int]) -> int:
        R,C=len(maze),len(maze[0]); er,ec=entrance
        q=deque([(er,ec,0)]); maze[er][ec]='+'
        while q:
            r,c,d=q.popleft()
            for dr,dc in[(1,0),(-1,0),(0,1),(0,-1)]:
                nr,nc=r+dr,c+dc
                if 0<=nr<R and 0<=nc<C and maze[nr][nc]=='.':
                    if nr==0 or nr==R-1 or nc==0 or nc==C-1: return d+1
                    maze[nr][nc]='+'; q.append((nr,nc,d+1))
        return -1

C++

class Solution {
public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance){
        int R=maze.size(),C=maze[0].size(),er=entrance[0],ec=entrance[1];
        queue<tuple<int,int,int>> q; q.push({er,ec,0}); maze[er][ec]='+';
        int dr[]={0,0,1,-1},dc[]={1,-1,0,0};
        while(!q.empty()){
            auto[r,c,d]=q.front();q.pop();
            for(int i=0;i<4;i++){
                int nr=r+dr[i],nc=c+dc[i];
                if(nr>=0&&nr<R&&nc>=0&&nc<C&&maze[nr][nc]=='.'){
                    if(nr==0||nr==R-1||nc==0||nc==C-1) return d+1;
                    maze[nr][nc]='+'; q.push({nr,nc,d+1});
                }
            }
        }
        return -1;
    }
};

Complexity

  • Time: O(mn) | Space: O(mn)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro