Skip to content

Commit dd5f5c4

Browse files
authored
Merge pull request #238 from paurush11/master
Rotten Oranges
2 parents b9a9e00 + 74ae716 commit dd5f5c4

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
#define f(i,a,b) for(int i = a;i<b;i++)
5+
class Solution
6+
{
7+
public:
8+
//Function to find minimum time required to rot all oranges.
9+
void solve(int r, int c, queue<pair<int,int>>&q, vector<vector<int>>&grid){
10+
int rr[4] = {-1,1,0,0};
11+
int cc[4] = {0,0,-1,1};
12+
for(int i = 0;i<4;i++){
13+
int nr = r + rr[i];
14+
int nc = c + cc[i];
15+
16+
if(nr<0 || nc<0 || nr>=grid.size()|| nc>=grid[0].size())continue;
17+
if(grid[nr][nc] == 1){
18+
grid[nr][nc] = 2;
19+
q.push({nr,nc});
20+
}
21+
22+
}
23+
}
24+
int orangesRotting(vector<vector<int>>& grid) {
25+
queue<pair<int,int>>q;
26+
f(i,0,grid.size()){
27+
f(j,0,grid[0].size()){
28+
if(grid[i][j] == 2){
29+
q.push({i,j});
30+
}
31+
}
32+
}
33+
int timer = -1;
34+
while(!q.empty()){
35+
int k = q.size();
36+
while(k--){
37+
int r = q.front().first;
38+
int c = q.front().second;
39+
q.pop();
40+
solve(r,c,q,grid);
41+
}
42+
timer++;
43+
}
44+
for(auto i: grid){
45+
for(auto j :i){
46+
if(j == 1)return -1;
47+
}
48+
49+
}
50+
return timer;
51+
52+
53+
}
54+
};
55+
56+
int main(){
57+
int tc;
58+
cin >> tc;
59+
while(tc--){
60+
int n, m;
61+
cin >> n >> m;
62+
vector<vector<int>>grid(n, vector<int>(m, -1));
63+
for(int i = 0; i < n; i++){
64+
for(int j = 0; j < m; j++){
65+
cin >> grid[i][j];
66+
}
67+
}
68+
Solution obj;
69+
int ans = obj.orangesRotting(grid);
70+
cout << ans << "\n";
71+
}
72+
return 0;
73+
} //

0 commit comments

Comments
 (0)