-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotting-oranges.cpp
More file actions
109 lines (89 loc) · 2.59 KB
/
rotting-oranges.cpp
File metadata and controls
109 lines (89 loc) · 2.59 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// 994. Rotting Oranges (7/10/57650)
// Runtime: 0 ms (93.76%) Memory: 16.78 MB (69.53%)
/*
* Time complexity: O(N*M) (bfs O(V + E))
* Space complexity O(V) if all rottens
*/
class Solution {
struct Cell
{
int x;
int y;
bool operator<(const Cell& other) const
{
if(x != other.x) return x < other.x;
return y < other.y;
}
};
public:
int orangesRotting(vector<vector<int>>& grid) {
ROWS = grid.size();
COLS = grid[0].size();
bool availableFresh = false;
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
if(grid[i][j] == 2)
{
frontier.push({i, j});
// processed.insert({i, j});
}
if(grid[i][j] == 1)
{
availableFresh = true;
}
}
}
if(frontier.empty() && availableFresh)
{
return -1;
}
return bfs(grid);
}
int bfs(auto& grid)
{
int minutes = 0;
while(! frontier.empty())
{
bool rottedThisRound = false;
// Frontier is filled with rotten oranges
// All sourranding oranges are affected at the same step
// Thus, the same minute affects
const auto frontierSize = frontier.size();
for (int i = 0; i < frontierSize; i++)
{
const auto curr = frontier.front(); frontier.pop();
for(const auto& [dx, dy] : directions)
{
const Cell next{curr.x + dx, curr.y + dy};
if(next.x >= 0 && next.x < ROWS && next.y >=0 && next.y < COLS
&& grid[next.x][next.y] == 1)
// && processed.find(next) == processed.end()
{
grid[next.x][next.y] = 2;
frontier.push(next);
// processed.insert(next);
rottedThisRound = true;
}
}
}
if(rottedThisRound) minutes++;
}
// check if there are left fresh oranges
for(int i = 0; i < ROWS; i++)
{
for(int j = 0; j < COLS; j++)
{
if(grid[i][j] == 1) return -1;
}
}
return minutes;
}
private:
int ROWS;
int COLS;
std::vector<Cell> directions = {{-1,0}, {0,1}, {1, 0}, {0, -1}};
std::queue<Cell> frontier;
// std::set<Cell> processed;
};