forked from anshuman8800/Interivew-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrottenOranges.cpp
More file actions
47 lines (43 loc) · 1.36 KB
/
rottenOranges.cpp
File metadata and controls
47 lines (43 loc) · 1.36 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
#include<bits/stdc++.h>
using namespace std;
int minimumTime(vector<vector<int>> &fruits){
int n = fruits.size(), m = fruits[0].size();
queue<pair<pair<int, int>, int>> q;
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(fruits[i][j] == 2) q.push({{i, j}, 0});
}
}
// bfs
int maxResult = 0;
while(!q.empty()){
auto curr = q.front();
q.pop();
maxResult = max(maxResult, curr.second);
int curri = curr.first.first, currj = curr.first.second;
if(curri - 1 >= 0 && fruits[curri-1][currj] == 1){
q.push({{curri-1, currj}, curr.second+1});
fruits[curri-1][currj] = 2;
}
if(curri + 1 < n && fruits[curri+1][currj] == 1){
q.push({{curri+1, currj}, curr.second+1});
fruits[curri+1][currj] = 2;
}
if(currj - 1 >= 0 && fruits[curri][currj-1] == 1){
q.push({{curri, currj-1}, curr.second+1});
fruits[curri][currj-1] = 2;
}
if(currj + 1 < m && fruits[curri][currj+1] == 1){
q.push({{curri, currj+1}, curr.second+1});
fruits[curri][currj+1] = 2;
}
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
if(fruits[i][j] == 1){
return -1;
}
}
}
return maxResult;
}