-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy path994. Rotting_Oranges.cpp
51 lines (47 loc) · 1.41 KB
/
994. 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
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
const vector<int> dirs{0, 1, 0, -1, 0};
auto isNeighborRotten = [&](int i, int j, const vector<vector<int>>& grid) {
for (int k = 0; k < 4; ++k) {
const int r = i + dirs[k];
const int c = j + dirs[k + 1];
if (r < 0 || r == m || c < 0 || c == n)
continue;
if (grid[r][c] == 2)
return true;
}
return false;
};
int ans = 0;
while (true) {
vector<vector<int>> nextGrid(m, vector<int>(n));
// Calculate `nextGrid` based on `grid`
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) { // Fresh
if (isNeighborRotten(
i, j, grid)) // Any of 4-directionally oranges is rotten
nextGrid[i][j] = 2;
else
nextGrid[i][j] = 1;
} else if (grid[i][j] == 2) { // Rotten
nextGrid[i][j] = 2; // Keep rotten
}
if (nextGrid == grid)
break;
grid = nextGrid;
++ans;
}
return any_of(
begin(grid), end(grid),
[&](vector<int>& row) {
return any_of(begin(row), end(row),
[&](int orange) { return orange == 1; });
})
? -1
: ans;
}
};