Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- class Solution
- {
- public:
- //Function to find minimum time required to rot all oranges.
- int orangesRotting(vector<vector<int>>& grid) {
- // Code here
- int n = grid.size();
- int m = grid[0].size();
- queue<pair<pair<int,int>,int>> q;
- int vis[n][m];
- int cntfresh=0;
- for(int i=0;i<grid.size();i++)
- {
- for(int j=0;j<grid[0].size();j++)
- {
- if(grid[i][j]==2)
- {
- q.push({{i,j},0});
- vis[i][j]=2;
- }
- else
- {
- vis[i][j]=0;
- }
- if(grid[i][j]==1)
- {
- cntfresh++;
- }
- }
- }
- int tm=0;
- int drow[] = {-1,0,1,0};
- int dcol[] = { 0,1,0,-1};
- int c=0;
- while(!q.empty())
- {
- int ni = q.front().first.first;
- int nj = q.front().first.second;
- int t = q.front().second;
- tm = max(tm,t);
- q.pop();
- for(int i=0;i<4;i++)
- {
- int row = ni+drow[i];
- int col = nj+dcol[i];
- if((row>=0 && row<n) && (col>=0 && col<m) && vis[row][col]==0 && grid[row][col]==1)
- {
- q.push({{row,col},t+1});
- vis[row][col]=2;
- c++;
- }
- }
- }
- if(c!=cntfresh)
- {
- 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
Advertisement
Add Comment
Please, Sign In to add comment