Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
- queue<pair<int,int>> q;
- int n=maze.size();
- int m=maze[0].size();
- q.push({entrance[0],entrance[1]});
- int dx[4]={-1,0,1,0};
- int dy[4]={0,1,0,-1};
- int step=0;
- maze[entrance[0]][entrance[1]]='+';
- while(!q.empty())
- {
- int s= q.size();
- while(s--)
- {
- auto curr = q.front();
- q.pop();
- int i=curr.first;
- int j=curr.second;
- if(!(i==entrance[0] && j==entrance[1]) && (i==0 || j==0 || i==n-1 || j==m-1))
- {
- return step;
- }
- for(int k=0;k<4;k++)
- {
- int n_i = i+dx[k];
- int n_j = j+dy[k];
- if((n_i>=0 && n_i<n) && (n_j>=0 && n_j<m) && maze[n_i][n_j]!='+')
- {
- maze[n_i][n_j]='+';
- q.push({n_i,n_j});
- }
- }
- }
- step++;
- }
- return -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment