-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotten Oranges (Leetcode)
42 lines (42 loc) · 1.31 KB
/
Rotten Oranges (Leetcode)
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
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
// Code here
int n = grid.size();
int m = grid[0].size();
queue<pair<int, int>> Queue;
int fresh = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 2)
Queue.push({i, j});
else if(grid[i][j] == 1)
fresh++;
}
}
pair<int, int> Pair[4] = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
int ans = -1;
while(!Queue.empty()) {
int s = Queue.size();
ans++;
for(int i = 0; i < s; i++) {
pair<int, int> temp = Queue.front();
Queue.pop();
int currX = temp.first;
int currY = temp.second;
for(int j = 0; j < 4; j++) {
int x = currX + Pair[j].first;
int y = currY + Pair[j].second;
if(x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1) {
Queue.push({x, y});
grid[x][y] = 2;
fresh--;
}
}
}
}
if(fresh > 0) return -1;
if(ans == -1) return 0;
return ans;
}
};