题目链接:力扣
本题也是多源bfs,和leetcode-994. 腐烂的橘子力扣思路差不多。本题需要单独开一个seen数组来判断每个网格是否已经被处理过。(之所以在第一次访问时就要把网格的状态记录为已处理,后续所有访问到该网格的情况不再被考虑, 是因为本题求的其实是最短路问题,而bfs求的最短路一定是第一次访问到该点时的路径长度)
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m=mat.size();
int n=mat[0].size();
queue<pair<int,int>> q;
vector<vector<int>> seen(m,vector<int> (n,0)); //0代表当前网格没被搜索过
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(!mat[i][j]){
q.push({i,j});
seen[i][j]=1;
}
}
}
vector<vector<int>> res(m,vector<int> (n,0));
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
while(q.size()){
auto t=q.front();
q.pop();
for(int i=0;i<4;i++){
int x=t.first+dx[i];
int y=t.second+dy[i];
if( x>=0 && x<m && y>=0 && y<n && !seen[x][y] ){ //这里不用判断mat[x][y]是否为0, 因为所有为0的mat[x][y]的对应flag值已经被初始化为1
res[x][y]=res[t.first][t.second]+1;
seen[x][y]=1;
q.push({x,y});
}
}
}
return res;
}
};
做这题的时候新学了一下二维vector的初始化方式,记录一下
//初始化一个3*4数组, 所有值初始化为100
vector<vector<int>> test(3,vector<int> (4,100));
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
cout<<test[i][j]<<" ";
}
cout<<endl;
}
/*output
100 100 100 100
100 100 100 100
100 100 100 100
*/