-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotten_Oranges.cpp
More file actions
74 lines (65 loc) · 1.99 KB
/
Rotten_Oranges.cpp
File metadata and controls
74 lines (65 loc) · 1.99 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <vector>
#include <queue>
class Solution {
public:
int orangesRotting(std::vector<std::vector<int>>& grid) {
int timeStep = 0;
std::queue<std::pair<int, int>> q;
int numFresh = 0;
int numRotten = 0;
int numRows = grid.size();
int numCols = grid[0].size();
// Insert all rotten oranges into the queue
for (int row=0; row<numRows; row++) {
for (int col=0; col<numCols; col++) {
if (grid[row][col] == 2) {
numRotten++;
q.push({row, col});
grid[row][col] = -1;
} else if (grid[row][col] == 1) {
numFresh++;
}
}
}
q.push({-1, -1}); // mark the decay of a minute
int numContaminated = 0;
while (!q.empty()) {
std::pair<int, int> curr = q.front();
q.pop();
if (curr.first == -1) {
timeStep++;
if (!q.empty()) {
q.push({-1,-1});
}
continue;
}
// Insert neighbours
int x = curr.first;
int y = curr.second;
if (x >= 1 && grid[x-1][y] == 1) {
q.push({x-1, y});
grid[x-1][y] = -1;
numContaminated++;
}
if (x < numRows-1 && grid[x+1][y] == 1) {
q.push({x+1,y});
grid[x+1][y] = -1;
numContaminated++;
}
if (y >= 1 && grid[x][y-1] == 1) {
q.push({x,y-1});
grid[x][y-1] = -1;
numContaminated++;
}
if (y < numCols-1 && grid[x][y+1] == 1) {
q.push({x, y+1});
grid[x][y+1] = -1;
numContaminated++;
}
}
if (numFresh != numContaminated) {
return -1;
}
return timeStep-1;
}
};