具体思想:
试一下图的bfs,dfs超时,不知道为什么,歪日;
个人不知道什么原因;
具体代码:
#define INF 2147483647
class Solution {
public:
const int dir[4][2] = {
{1,0},{0,1},{-1,0},{0,-1},
};
void wallsAndGates(vector<vector<int>>& rooms) {
int m = rooms.size(), n = rooms[0].size();
queue<pair<int,int>> q;
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
if(rooms[i][j] == 0) q.push({i,j});
}
}
while(!q.empty()){
int x = q.front().first, y = q.front().second;
int step = 0;
for(auto& d : dir){
int posx = x + d[0], posy = y + d[1];
if(posx < 0 || posx >= m || posy < 0 || posy >= n || rooms[posx][posy] != INF)
continue; //每次可以更新的[posx][posy]位置都可以确定一定是最小的
rooms[posx][posy] = rooms[x][y] + 1;
q.push({posx,posy});
}
q.pop();
}
}
};