Rotten Oranges | Practice | GeeksforGeeks

Given a grid of dimension nxm where each cell in the grid can have values 0, 1 or 2 which has the following meaning:
0 : Empty cell 
1 : Cells have fresh oranges 
2 : Cells have rotten oranges 
We have to determine what is the minimum time required to rot all oranges. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. 
 
Example 1:
Input: grid = {{0,1,2},{0,1,2},{2,1,1}}
Output: 1
Explanation: The grid is-
0 1 2
0 1 2
2 1 1
Oranges at positions (0,2), (1,2), (2,0)
will rot oranges at (0,1), (1,1), (2,2) and 
(2,1) in unit time.

Example 2:
Input: grid = {{2,2,0,1}}
Output: -1
Explanation: The grid is-
2 2 0 1
Oranges at (0,0) and (0,1) can't rot orange at
(0,3).

 
Your Task:
You don't need to read or print anything, Your task is to complete the function orangesRotting() which takes grid as input parameter and returns the minimum time to rot all the fresh oranges. If not possible returns -1.
 
Expected Time Complexity: O(n*m)
Expected Auxiliary Space: O(n)
 
Constraints:
1 ≤ n, m ≤ 500
-1
danish_nitdgp1 week ago
C++ Approach without using delimiter.    bool isvalid(int i, int j,vector<vector<int>>& grid)   {    int R = grid.size();    int C = grid[0].size();       return (i >= 0 && j >= 0 && i < R && j < C) && grid[i][j] == 1;   }      struct Oranges{    int timeframe;    int x;    int y;   };      bool checkIfFreshOrangeIsRemaining(vector<vector<int>>& grid)   {    int R = grid.size();    int C = grid[0].size();       for (int i=0; i<R; i++)          for (int j=0; j<C; j++)             if (grid[i][j] == 1)                return true;       return false;   }      int orangesRotting(vector<vector<int>>& grid) {       int R = grid.size();       int C = grid[0].size();       int ans = 0;       queue<Oranges> q;          Oranges temp;          for (int i=0; i<R; i++)       {          for (int j=0; j<C; j++)          {               if (grid[i][j] == 2)               {                   temp.x = i;                   temp.y = j;                   temp.timeframe = 0;                   q.push(temp);               }           }       }       while(!q.empty()){        temp = q.front();        if(isvalid(temp.x+1,temp.y,grid)){         grid[temp.x+1][temp.y] = 2;         temp.x++;         temp.timeframe++;         q.push(temp);         temp.x--;         temp.timeframe--;        }        if(isvalid(temp.x-1,temp.y,grid)){         grid[temp.x-1][temp.y] = 2;         temp.x--;         temp.timeframe++;         q.push(temp);         temp.x++;         temp.timeframe--;        }        if(isvalid(temp.x,temp.y+1,grid)){         grid[temp.x][temp.y+1] = 2;         temp.y++;         temp.timeframe++;         q.push(temp);         temp.y--;         temp.timeframe--;        }        if(isvalid(temp.x,temp.y-1,grid)){         grid[temp.x][temp.y-1] = 2;         temp.y--;         temp.timeframe++;         q.push(temp);         temp.y++;         temp.timeframe--;        }        Oranges last;        last = q.front();        ans = last.timeframe;        q.pop();       }       if(checkIfFreshOrangeIsRemaining(grid)) return -1;       return ans;      }
0
sanjeevranjan12091 week ago
Easy python solution by BFS
 
def orangesRotting(self, grid):    def rotting(rotten):        temp = []        for i,j in rotten:            if i>0 and grid[i-1][j] == 1:                temp.append((i-1,j))                grid[i-1][j]=2                            if i<len(grid)-1 and grid[i+1][j] == 1:                temp.append((i+1,j))                grid[i+1][j]=2                            if j>0 and grid[i][j-1] == 1:                temp.append((i,j-1))                grid[i][j-1]=2                            if j<len(grid[0])-1 and grid[i][j+1] == 1:                temp.append((i,j+1))                grid[i][j+1]=2                        return temp            q=deque()    count = 0    for row in range(len(grid)):        for col in range(len(grid[row])):            if grid[row][col] == 2:                q.append((row,col))                    while q:        q = rotting(q)        if len(q) == 0:            break        count+=1             for r in range(len(grid)):        for c in range(len(grid[0])):            if grid[r][c] == 1:                return -1    return count
+2
gaurabhkumarjha271020012 weeks ago
// c++
 if (g.empty()) return -1;
        
         int n= g.size();
         int m= g[0].size();
        
          queue <pair <int,int>> q; 
          int freshorange=0;
          for (int i=0; i< n; i++){
              
               for (int j=0; j< m; j++){
                   
              if (g[i][j] == 1) freshorange++;
             else if (g[i][j] == 2) q.push({i,j});
               }
          }
       int time=0;
 vector <pair <int,int> > v= {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
          while (freshorange!=0 and !q.empty()){
              
               int sz= q.size();
              for (int i=0; i< sz; i++){
                  
                   int row= q.front().first;
                   int col= q.front().second;
                   q.pop();
                  
                   for (auto d: v){
                       
                        int rowx= row+d.first;
                        int coly= col+d.second; 
          if (rowx >= 0 and rowx < n and coly >=0 and coly < m and g[rowx][coly] == 1){
                      
                       g[rowx][coly]= 2;
                        freshorange--;
                      q.push({rowx,coly});
                  }
                }
         
              }
               time ++;
          }
        
          return freshorange==0?time:-1;
0
19bcs13143 weeks ago
class Pair{
    int i, j;
    Pair(int i,int j){
        this.i=i;
        this.j=j;
    }
}
class Solution
{
    //Function to find minimum time required to rot all oranges. 
    public int orangesRotting(int[][] g)
    {
        // Code here
        int r=g.length,c=g[0].length;
        Queue<Pair> q= new ArrayDeque<>();
        
        
        for(int i=0;i<g.length;i++){
            for(int j=0;j<g[0].length;j++){
                if(g[i][j]==2){
                    q.add(new Pair(i,j));
                    
                }
            }
        }
        
        int time=0;
        while(q.size()!=0){
            
            boolean flag=false;
            int siz=q.size();
           
            for(int k=0;k<siz;k++){
                Pair temp=q.remove();
                int i=temp.i,j=temp.j;
                
                for(int z=0;z<4;z++){
                    
                    if(isValid(g,r,c,i+dx[z],j+dy[z])){
                        flag=true;
                        q.add(new Pair(i+dx[z],j+dy[z]));
                        g[i+dx[z]][j+dy[z]]=2;
                        
                    }
                }
                
            }
            
            if(flag==true){
                time++;
            }
            
        }
        
        for(int i=0;i<g.length;i++){
            for(int j=0;j<g[0].length;j++){
                if(g[i][j]==1){
                    return -1;
                    
                }
            }
        }
        return time;
    }
    
    
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    
    public boolean isValid(int[][] g,int r,int c,int x,int y){
        if(x>=r || x<0 || y<0 || y>=c || g[x][y]==2 || g[x][y]==0){
            return false;
        }
        return true;
    }
    
    
    
}
+1
amarrajsmart1973 weeks ago
C++ Solution.
 
  int orangesRotting(vector<vector<int>>& grid) {       // Code here       queue<pair<int,int>> q;       int r=grid.size();       int c=grid[0].size();       int i,j;       int count=0;       for( i=0;i<r;i++)       {           for( j=0;j<c;j++)           {               if(grid[i][j]==2)               q.push({i,j});           }       }       q.push({-1,-1});       while(!q.empty())       {           i=q.front().first;           j=q.front().second;           if(i==-1&&j==-1&&q.size()==1)           {               q.pop();               break;           }           else if(i==-1&&j==-1&&q.size()>1)           {               count++;               q.pop();               q.push({-1,-1});           }                      else           {                if(i-1>=0&&grid[i-1][j]==1)               {                   grid[i-1][j]=2;                   q.push({i-1,j});               }               if(i+1<r&&grid[i+1][j]==1)               {                   grid[i+1][j]=2;                   q.push({i+1,j});               }                 if(j-1>=0&&grid[i][j-1]==1)                 {                     grid[i][j-1]=2;                     q.push({i,j-1});                 }                 if(j+1<c&&grid[i][j+1]==1)                 {                     grid[i][j+1]=2;                     q.push({i,j+1});                 }                 q.pop();                                         }       }         for( i=0;i<r;i++)       {           for( j=0;j<c;j++)           {               if(grid[i][j]==1)               return -1;           }       }       return count;         }
0
hamidnourashraf4 weeks ago
Time: 1.4/14.9
 
class Solution:
    def is_valid_index(self, i, j, n, m):
        if i < 0 or i >= n or j < 0 or j >= m:
            return False
        return True
    def update_grid(self, grid, n, m, aux_dict):
        cnt = 0
        aux_set = set()
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    if self.is_valid_index(i-1, j, n, m) and grid[i-1][j] == 2 and ((i-1, j) not in aux_set):
                        aux_set.add((i,j))
                        grid[i][j] = 2
                        cnt += 1
                        del aux_dict[(i,j)]
                    elif self.is_valid_index(i+1, j, n, m) and grid[i+1][j] == 2 and ((i+1, j) not in aux_set):
                        aux_set.add((i,j))
                        grid[i][j] = 2
                        cnt += 1
                        del aux_dict[(i,j)]
                    elif self.is_valid_index(i, j-1, n, m) and grid[i][j-1] == 2 and ((i, j-1) not in aux_set):
                        aux_set.add((i,j))
                        grid[i][j] = 2
                        cnt += 1
                        del aux_dict[(i,j)]
                    elif self.is_valid_index(i, j+1, n, m) and grid[i][j+1] == 2 and ((i, j+1) not in aux_set):
                        aux_set.add((i,j))
                        grid[i][j] = 2
                        cnt += 1
                        del aux_dict[(i,j)]
        return cnt

    def orangesRotting(self, grid):
        aux_dict = dict()
        n = len(grid)
        m = len(grid[0])
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    aux_dict[(i,j)]= 1
        time = 0
        while len(aux_dict) > 0:
            time += 1
            changes = self.update_grid(grid, n, m, aux_dict)
            if changes == 0 and len(aux_dict) > 0:
                return -1
        return time

0
krishnachitlangi2
This comment was deleted.
0
milindprajapatmst191 month ago
HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!!

int dx[] = {-1,  0, 1, 0};
int dy[] = { 0, -1, 0, 1};

class Node {
    public:
    int i, j, dist;
    Node(int i, int j, int dist) {
        this->i = i; this->j = j; this->dist = dist;
    }
};

class Solution {
    public:
    // multi-source bfs 
    int orangesRotting(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size(), cnt = 0, dist = 0;
        queue<Node> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1)
                    cnt++;
                else if (grid[i][j] == 2)
                    q.push(Node(i, j, dist));
            }
        }
        while (!q.empty()) {
            int sz = q.size();
            while(sz--) {
                Node& p = q.front();
                q.pop();
                for (int k = 0; k < 4; k++) {
                    int i = p.i + dx[k], j = p.j + dy[k];
                    if (0 <= i && i < n && 0 <= j && j < m && grid[i][j] == 1) {
                        cnt--;
                        q.push(Node(i, j, p.dist + 1));
                        grid[i][j] = 2;
                    }
                }
                dist = max(dist, p.dist);
            }
        }
        return (cnt == 0) ? dist : -1;
    }
};
0
rahulgupta067891 month ago
int orangesRotting(vector<vector<int>>& grid) {       // Code here      queue<pair<int,int>> q;              int r = grid.size();       int c = grid[0].size();       int level = 0,rtemp,ctemp,size;              for(int i=0;i<r;++i){           for(int j=0;j<c;++j){               if(grid[i][j]==2)                   q.push({i,j});           }       }              while(!q.empty()){           ++level;           size=q.size();           while(size-->0){               rtemp = q.front().first;               ctemp = q.front().second;               q.pop();               if(rtemp>0 && grid[rtemp-1][ctemp]==1){                   q.push({rtemp-1,ctemp});                   grid[rtemp-1][ctemp]=2;               }               if(ctemp>0 && grid[rtemp][ctemp-1]==1){                   q.push({rtemp,ctemp-1});                   grid[rtemp][ctemp-1]=2;               }               if(rtemp<r-1 && grid[rtemp+1][ctemp]==1){                   q.push({rtemp+1,ctemp});                   grid[rtemp+1][ctemp]=2;               }               if(ctemp<c-1 && grid[rtemp][ctemp+1]==1){                   q.push({rtemp,ctemp+1});                   grid[rtemp][ctemp+1]=2;               }           }       }       for(int i=0;i<r;++i){           for(int j=0;j<c;++j){               if(grid[i][j]==1){                   return -1;               }           }       }       return max(0,level-1);   }
-1
sanketgharatkar1231 month ago
//   CPP best solution -- 0.5 sec
   
   
   int orangesRotting(vector<vector<int>>& grid) {
        int m=grid.size();
        int n=grid[0].size();
        queue<pair<int,int>> qu;
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[0].size();j++)
            {
                if(grid[i][j]==2)
                {
                    qu.push({i,j});
                }
            }
        }
        int count=0;
        while(qu.empty()==false)
        {
            int siz=qu.size();
            
            while(siz--)
            {
                pair<int,int> p1=qu.front();
                qu.pop();
                
                if(p1.first+1<m and grid[p1.first+1][p1.second]==1)
                {
                    grid[p1.first+1][p1.second]=2;
                    qu.push({p1.first+1,p1.second});
                }
                if(p1.first-1>=0 and grid[p1.first-1][p1.second]==1)
                {
                    grid[p1.first-1][p1.second]=2;
                    qu.push({p1.first-1,p1.second});
                }
                if(p1.second+1<n and grid[p1.first][p1.second+1]==1)
                {
                    grid[p1.first][p1.second+1]=2;
                    qu.push({p1.first,p1.second+1});
                }
                if(p1.second-1>=0 and grid[p1.first][p1.second-1]==1)
                {
                    grid[p1.first][p1.second-1]=2;
                    qu.push({p1.first,p1.second-1});
                }                
            }
            
            if(qu.size()==0)
            {
                if(count==0)
                {   count=-1;
                    
                }
                
                break;
            }
            
            
            count++;
        }
        
        
        for(int i=0;i<grid.size();i++)
        {
            for(int j=0;j<grid[0].size();j++)
            {
                if(grid[i][j]==1)
                {
                    return -1;
                }
            }
        }        
        
        
        
        
        return count;
        
        
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.