forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walls-and-gates.cpp
34 lines (33 loc) · 1.02 KB
/
walls-and-gates.cpp
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
// Time: O(m * n)
// Space: O(g)
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
const int INF = numeric_limits<int>::max();
queue<pair<int, int>> q;
for (int i = 0; i < rooms.size(); ++i) {
for (int j = 0; j < rooms[0].size(); ++j) {
if (rooms[i][j] == 0) {
q.emplace(i, j);
}
}
}
while (!q.empty()) {
int i, j;
tie(i, j) = q.front();
q.pop();
for (const pair<int, int>& d :
vector<pair<int, int>>{{i + 1, j}, {i - 1, j},
{i, j + 1}, {i, j - 1}}) {
int I, J;
tie(I, J) = d;
if (I >= 0 && I < rooms.size() &&
J >= 0 && J < rooms[0].size() &&
rooms[I][J] == INF) {
rooms[I][J] = rooms[i][j] + 1;
q.emplace(I, J);
}
}
}
}
};