Skip to content

Commit 517831b

Browse files
authored
Create rotting-oranges.cpp
1 parent 6e9b27a commit 517831b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

C++/rotting-oranges.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Time: O(m * n)
2+
// Space: O(m * n)
3+
4+
class Solution {
5+
public:
6+
int orangesRotting(vector<vector<int>>& grid) {
7+
static const vector<pair<int, int>> directions{{0, 1}, {1, 0},
8+
{0, -1}, {-1, 0}};
9+
10+
int count = 0;
11+
queue<tuple<int, int, int>> q;
12+
for (int r = 0; r < grid.size(); ++r) {
13+
for (int c = 0; c < grid[r].size(); ++c) {
14+
if (grid[r][c] == 2) {
15+
q.emplace(r, c, 0);
16+
} else if (grid[r][c] == 1) {
17+
++count;
18+
}
19+
}
20+
}
21+
22+
int result = 0;
23+
while (!q.empty()) {
24+
int r, c;
25+
tie(r, c, result) = q.front(); q.pop();
26+
for (const auto& d : directions) {
27+
int nr = r + d.first, nc = c + d.second;
28+
if (!(0 <= nr && nr < grid.size() &&
29+
0 <= nc && nc < grid[r].size())) {
30+
continue;
31+
}
32+
if (grid[nr][nc] == 1) {
33+
--count;
34+
grid[nr][nc] = 2;
35+
q.emplace(nr, nc, result + 1);
36+
}
37+
}
38+
}
39+
return (count == 0) ? result : -1;
40+
}
41+
};

0 commit comments

Comments
 (0)