很简单的广度优先遍历和542,1091差不多
class Solution {
public:
class pos
{
public:
int x_;
int y_;
pos(int x,int y):x_(x),y_(y){};
};
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
if(maze[entrance[0]][entrance[1]]=='+')
return -1;
queue<pos>a;
a.push(pos(entrance[0], entrance[1]));
maze[entrance[0]][entrance[1]] = 'x';
int ret = 1;
while(!a.empty())
{
queue<pos>b;
while(!a.empty())
{
auto pos_tmp = a.front();
a.pop();
if(pos_tmp.x_-1>=0 && maze[pos_tmp.x_-1][pos_tmp.y_]=='.')
{
if(pos_tmp.x_-1==0 || pos_tmp.x_-1==maze.size()-1||pos_tmp.y_==0||pos_tmp.y_==maze[0].size()-1)
return ret;
b.push(pos(pos_tmp.x_-1,pos_tmp.y_));
maze[pos_tmp.x_-1][pos_tmp.y_] = 'x';
}
if(pos_tmp.y_-1>=0 && maze[pos_tmp.x_][pos_tmp.y_-1]=='.')
{
if(pos_tmp.x_==0 || pos_tmp.x_==maze.size()-1||pos_tmp.y_-1==0||pos_tmp.y_-1==maze[0].size()-1)
return ret;
b.push(pos(pos_tmp.x_,pos_tmp.y_-1));
maze[pos_tmp.x_][pos_tmp.y_-1] = 'x';
}
if(pos_tmp.x_+1<maze.size() && maze[pos_tmp.x_+1][pos_tmp.y_]=='.')
{
if(pos_tmp.x_+1==0 || pos_tmp.x_+1==maze.size()-1||pos_tmp.y_==0||pos_tmp.y_==maze[0].size()-1)
return ret;
b.push(pos(pos_tmp.x_+1,pos_tmp.y_));
maze[pos_tmp.x_+1][pos_tmp.y_] = 'x';
}
if(pos_tmp.y_+1<maze[0].size() && maze[pos_tmp.x_][pos_tmp.y_+1]=='.')
{
if(pos_tmp.x_==0 || pos_tmp.x_==maze.size()-1||pos_tmp.y_+1==0||pos_tmp.y_+1==maze[0].size()-1)
return ret;
b.push(pos(pos_tmp.x_,pos_tmp.y_+1));
maze[pos_tmp.x_][pos_tmp.y_+1] = 'x';
}
}
if(b.empty())
return -1;
swap(a,b);
++ret;
}
return ret;
}
};