1091. 二进制矩阵中的最短路径
上代码
class Solution {
public:
int bfs(vector<vector<int>>& grid)
{
queue<pair<int,int>> q;
int step=1;
if(grid.size()==1) return 1;
q.push(make_pair(0,0));
int dx[]={0,0,1,1,-1,-1,1,-1};
int dy[]={1,-1,1,-1,-1,1,0,0};
while(!q.empty())
{
int n=q.size();
step++;
for(int j=0;j<n;j++)
{
int x=q.front().first;
int y=q.front().second;
q.pop();
// cout<<x<<' '<<y;
for(int i=0;i<8;i++)
{
int nx=x+dx[i];
int ny=y+dy[i];
if(nx<0||ny<0||nx>=grid.size()||ny>=grid.size())
continue;
if(nx==grid.size()-1&&ny==grid.size()-1&&grid[nx][ny]==0)
{
return step;
break;
}
else if(grid[nx][ny]==0)
{
grid[nx][ny]=1;
q.push(make_pair(nx,ny));
}
}
}
}
return -1;
}
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if(grid.empty()) return -1;
if(grid[0][0] == 1 || grid[grid.size()-1][grid.size()-1] == 1) return -1;
return bfs(grid);
}
};
提交情况