forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rotting-oranges.cpp
41 lines (38 loc) · 1.24 KB
/
rotting-oranges.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
35
36
37
38
39
40
41
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
{0, -1}, {-1, 0}};
int count = 0;
queue<tuple<int, int, int>> q;
for (int r = 0; r < grid.size(); ++r) {
for (int c = 0; c < grid[r].size(); ++c) {
if (grid[r][c] == 2) {
q.emplace(r, c, 0);
} else if (grid[r][c] == 1) {
++count;
}
}
}
int result = 0;
while (!q.empty()) {
int r, c;
tie(r, c, result) = q.front(); q.pop();
for (const auto& d : directions) {
int nr = r + d.first, nc = c + d.second;
if (!(0 <= nr && nr < grid.size() &&
0 <= nc && nc < grid[r].size())) {
continue;
}
if (grid[nr][nc] == 1) {
--count;
grid[nr][nc] = 2;
q.emplace(nr, nc, result + 1);
}
}
}
return (count == 0) ? result : -1;
}
};