jayati

Rotten Oranges

Oct 10th, 2023
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution
  7. {
  8.     public:
  9.     //Function to find minimum time required to rot all oranges.
  10.     int orangesRotting(vector<vector<int>>& grid) {
  11.         // Code here
  12.         int n = grid.size();
  13.         int m = grid[0].size();
  14.         queue<pair<pair<int,int>,int>> q;
  15.         int vis[n][m];
  16.         int cntfresh=0;
  17.         for(int i=0;i<grid.size();i++)
  18.         {
  19.             for(int j=0;j<grid[0].size();j++)
  20.             {
  21.                 if(grid[i][j]==2)
  22.                 {
  23.                     q.push({{i,j},0});
  24.                     vis[i][j]=2;
  25.                 }
  26.                 else
  27.                 {
  28.                     vis[i][j]=0;
  29.                 }
  30.                 if(grid[i][j]==1)
  31.                 {
  32.                     cntfresh++;
  33.                 }
  34.             }
  35.         }
  36.         int tm=0;
  37.         int drow[] = {-1,0,1,0};
  38.         int dcol[] = { 0,1,0,-1};
  39.         int c=0;
  40.         while(!q.empty())
  41.         {
  42.             int ni = q.front().first.first;
  43.             int nj = q.front().first.second;
  44.             int t = q.front().second;
  45.             tm = max(tm,t);
  46.             q.pop();
  47.            
  48.             for(int i=0;i<4;i++)
  49.             {
  50.                 int row = ni+drow[i];
  51.                 int col = nj+dcol[i];
  52.                 if((row>=0 && row<n) && (col>=0 && col<m) && vis[row][col]==0 && grid[row][col]==1)
  53.                 {
  54.                     q.push({{row,col},t+1});
  55.                     vis[row][col]=2;
  56.                     c++;
  57.                 }
  58.             }
  59.         }
  60.         if(c!=cntfresh)
  61.         {
  62.             return -1;
  63.         }
  64.         return tm;
  65.     }
  66. };
  67.  
  68. //{ Driver Code Starts.
  69. int main(){
  70.     int tc;
  71.     cin >> tc;
  72.     while(tc--){
  73.         int n, m;
  74.         cin >> n >> m;
  75.         vector<vector<int>>grid(n, vector<int>(m, -1));
  76.         for(int i = 0; i < n; i++){
  77.             for(int j = 0; j < m; j++){
  78.                 cin >> grid[i][j];
  79.             }
  80.         }
  81.         Solution obj;
  82.         int ans = obj.orangesRotting(grid);
  83.         cout << ans << "\n";
  84.     }
  85.     return 0;
  86. }
  87. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment