-
Notifications
You must be signed in to change notification settings - Fork 0
/
Walls and Gates 1
35 lines (35 loc) · 1.28 KB
/
Walls and Gates 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
if (rooms.empty()) return;
int m = rooms.size(), n = rooms[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!rooms[i][j]) {
queue<Grid> grids;
grids.push(Grid(i + 1, j, 1));
grids.push(Grid(i - 1, j, 1));
grids.push(Grid(i, j + 1, 1));
grids.push(Grid(i, j - 1, 1));
while (!grids.empty()) {
Grid grid = grids.front();
grids.pop();
int r = grid.r, c = grid.c, d = grid.d;
if (r < 0 || r >= m || c < 0 || c >= n || rooms[r][c] < d)
continue;
rooms[r][c] = d;
grids.push(Grid(r + 1, c, d + 1));
grids.push(Grid(r - 1, c, d + 1));
grids.push(Grid(r, c + 1, d + 1));
grids.push(Grid(r, c - 1, d + 1));
}
}
}
}
}
private:
struct Grid {
int r, c, d;
Grid(int _r, int _c, int _d) : r(_r), c(_c), d(_d) {}
};
};