jayati

Nearest Exit from Entrance in Maze

May 29th, 2024
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
  5.         queue<pair<int,int>> q;
  6.         int n=maze.size();
  7.         int m=maze[0].size();
  8.         q.push({entrance[0],entrance[1]});
  9.         int dx[4]={-1,0,1,0};
  10.         int dy[4]={0,1,0,-1};
  11.         int step=0;
  12.         maze[entrance[0]][entrance[1]]='+';
  13.         while(!q.empty())
  14.         {
  15.             int s= q.size();
  16.             while(s--)
  17.             {
  18.                 auto curr = q.front();
  19.                 q.pop();
  20.                 int i=curr.first;
  21.                 int j=curr.second;
  22.                 if(!(i==entrance[0] && j==entrance[1]) && (i==0 || j==0 || i==n-1 || j==m-1))
  23.                 {
  24.                     return step;
  25.                 }
  26.                 for(int k=0;k<4;k++)
  27.                 {
  28.                      int n_i = i+dx[k];
  29.                      int n_j = j+dy[k];
  30.  
  31.                      if((n_i>=0 && n_i<n) && (n_j>=0 && n_j<m) && maze[n_i][n_j]!='+')
  32.                      {
  33.                         maze[n_i][n_j]='+';
  34.                         q.push({n_i,n_j});
  35.                      }
  36.                 }
  37.             }
  38.             step++;
  39.         }
  40.         return -1;
  41.        
  42.  
  43.        
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment