286.墙与门 (Medium)*
题目描述*

标签*
广度优先搜索;
思路*
经典的多源 bfs,从每个门的位置出发向外扩散,遇到空房间就填入距离值。
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
int m = rooms.size();
if(m == 0) {
return;
}
int n = rooms[0].size();
if(n == 0) {
return;
}
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(make_pair(i, j));
}
}
}
vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int depth = 0;
while(!q.empty()) {
// int len = q.size();
// while(len--) {
int x = q.front().first;
int y = q.front().second;
q.pop();
for(auto d : dirs) {
int nextX = d.first + x;
int nextY = d.second + y;
if(nextX < 0 || nextY < 0 || nextX >= m || nextY >= n || rooms[nextX][nextY] == -1) {
continue;
}
if(rooms[nextX][nextY] > rooms[x][y] + 1) {
rooms[nextX][nextY] = rooms[x][y] + 1;
q.push(make_pair(nextX, nextY));
}
}
// }
}
}
};
最后更新: July 23, 2022