-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotten_Oranges.cpp
92 lines (83 loc) · 2.13 KB
/
Rotten_Oranges.cpp
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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
int orangesRotting(vector<vector<int>> &grid)
{
int n = grid.size();
int m = grid[0].size();
int delRow[] = {-1, 0, +1, 0};
int delCol[] = {0, +1, 0, -1};
queue<pair<pair<int, int>, int>> q;
int vis[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (grid[i][j] == 2)
{
q.push({{i, j}, 0});
vis[i][j] = 2;
}
else
vis[i][j] = 0;
}
}
int tm = 0;
while (!q.empty())
{
int r = q.front().first.first;
int c = q.front().first.second;
int t = q.front().second;
tm = max(tm, t);
q.pop();
for (int i = 0; i < 4; i++)
{
int nrow = r + delRow[i];
int ncol = c + delCol[i];
if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m &&
vis[nrow][ncol] != 2 && grid[nrow][ncol] == 1)
{
q.push({{nrow, ncol}, t + 1});
vis[nrow][ncol] = 2;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (vis[i][j] != 2 && grid[i][j] == 1)
return -1;
}
}
return tm;
}
};
//{ Driver Code Starts.
int main()
{
int tc;
cin >> tc;
while (tc--)
{
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m, -1));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> grid[i][j];
}
}
Solution obj;
int ans = obj.orangesRotting(grid);
cout << ans << "\n";
}
return 0;
}
// } Driver Code Ends