Given a matrix of dimension m*n where each cell in the matrix 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
Determine what is the minimum time required so that all the oranges become rotten. 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). If it is impossible to rot every orange then simply return -1.
Examples:
Input: arr[][C] = { {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
Output:
All oranges can become rotten in 2-time frames.
Explanation:
At 0th time frame:
{2, 1, 0, 2, 1}
{1, 0, 1, 2, 1}
{1, 0, 0, 2, 1}
At 1st time frame:
{2, 2, 0, 2, 2}
{2, 0, 2, 2, 2}
{1, 0, 0, 2, 2}
At 2nd time frame:
{2, 2, 0, 2, 2}
{2, 0, 2, 2, 2}
{2, 0, 0, 2, 2}
Input: arr[][C] = { {2, 1, 0, 2, 1},
{0, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
Output:
All oranges cannot be rotten.
Explanation:
At 0th time frame:
{2, 1, 0, 2, 1}
{0, 0, 1, 2, 1}
{1, 0, 0, 2, 1}
At 1st time frame:
{2, 2, 0, 2, 2}
{0, 0, 2, 2, 2}
{1, 0, 0, 2, 2}
At 2nd time frame:
{2, 2, 0, 2, 2}
{0, 0, 2, 2, 2}
{1, 0, 0, 2, 2}
...
The 1 at the bottom left corner of the matrix is never rotten.
Naive Solution:
- Approach: The idea is very basic. Traverse through all oranges in multiple rounds. In every round, rot the oranges to the adjacent position of oranges which were rotten in last round.
- Algorithm:
- Create a variable no = 2 and changed = false
- Run a loop until there is no cell of the matrix which is changed in a iteration.
- Run a nested loop and traverse the matrix. If the element of the matrix is equal to no then assign the adjacent elements to no + 1 if the adjacent elements value is equal to 1, i.e. not rotten and update changed to true.
- Traverse the matrix and check if there are any cell which is 1. If 1 is present return -1
- Else return no – 2
-
Implementation:
// C++ program to rot all oranges when u can move// in all the four direction from a rotten orange#include <bits/stdc++.h>usingnamespacestd;constintR = 3;constintC = 5;// Check if i, j is under the array limits of row and columnboolissafe(inti,intj){if(i >= 0 && i < R && j >= 0 && j < C)returntrue;returnfalse;}introtOranges(intv[R][C]){boolchanged =false;intno = 2;while(true) {for(inti = 0; i < R; i++) {for(intj = 0; j < C; j++) {// Rot all other oranges present at// (i+1, j), (i, j-1), (i, j+1), (i-1, j)if(v[i][j] == no) {if(issafe(i + 1, j) && v[i + 1][j] == 1) {v[i + 1][j] = v[i][j] + 1;changed =true;}if(issafe(i, j + 1) && v[i][j + 1] == 1) {v[i][j + 1] = v[i][j] + 1;changed =true;}if(issafe(i - 1, j) && v[i - 1][j] == 1) {v[i - 1][j] = v[i][j] + 1;changed =true;}if(issafe(i, j - 1) && v[i][j - 1] == 1) {v[i][j - 1] = v[i][j] + 1;changed =true;}}}}// if no rotten orange found it means all// oranges rottened nowif(!changed)break;changed =false;no++;}for(inti = 0; i < R; i++) {for(intj = 0; j < C; j++) {// if any orange is found to be// not rotten then ans is not possibleif(v[i][j] == 1)return-1;}}// Because initial value for a rotten// orange was 2returnno - 2;}// Driver functionintmain(){intv[R][C] = { { 2, 1, 0, 2, 1 },{ 1, 0, 1, 2, 1 },{ 1, 0, 0, 2, 1 } };cout <<"Max time incurred: "<< rotOranges(v);return0;}chevron_rightfilter_noneOutput:Max time incurred: 2
-
Complexity Analysis:
- Time Complexity : O(max(R,C) * R *C).
The matrix needs to be traversed again and again until there is no change in the matrix, that can happen max(R,C) times. So time complexity is O(max(R,C) * R *C). - Space Complexity:O(1).
No extra space is required.
- Time Complexity : O(max(R,C) * R *C).
Efficient Solution
- Approach: The idea is to use Breadth First Search. The condition of oranges getting rotten is when they come in contact with other rotten oranges. This is similar to breadth-first search where the graph is divided into layers or circles and the search is done from lower or closer layers to deeper or higher layers. In the previous approach, the idea was based on BFS but the implementation was poor and inefficient. To find the elements whose values are no the whole matrix had to be traversed. So that time can be reduced by using this efficient approach of BFS.
- Algorithm:
- Create an empty queue Q.
- Find all rotten oranges and enqueue them to Q. Also enqueue a delimiter to indicate the beginning of next time frame.
- Run a loop While Q is not empty
- Do following while delimiter in Q is not reached
- Dequeue an orange from the queue, rot all adjacent oranges. While rotting the adjacent, make sure that the time frame is incremented only once. And the time frame is not incremented if there are no adjacent oranges.
- Dequeue the old delimiter and enqueue a new delimiter. The oranges rotten in the previous time frame lie between the two delimiters.
- Create an empty queue Q.
-
Dry run of the above approach:
-
Implementation:
C++
// C++ program to find minimum time required to make all// oranges rotten#include<bits/stdc++.h>#define R 3#define C 5usingnamespacestd;// function to check whether a cell is valid / invalidboolisvalid(inti,intj){return(i >= 0 && j >= 0 && i < R && j < C);}// structure for storing coordinates of the cellstructele {intx, y;};// Function to check whether the cell is delimiter// which is (-1, -1)boolisdelim(ele temp){return(temp.x == -1 && temp.y == -1);}// Function to check whether there is still a fresh// orange remainingboolcheckall(intarr[][C]){for(inti=0; i<R; i++)for(intj=0; j<C; j++)if(arr[i][j] == 1)returntrue;returnfalse;}// This function finds if it is possible to rot all oranges or not.// If possible, then it returns minimum time required to rot all,// otherwise returns -1introtOranges(intarr[][C]){// Create a queue of cellsqueue<ele> Q;ele temp;intans = 0;// Store all the cells having rotten orange in first time framefor(inti=0; i<R; i++){for(intj=0; j<C; j++){if(arr[i][j] == 2){temp.x = i;temp.y = j;Q.push(temp);}}}// Separate these rotten oranges from the oranges which will rotten// due the oranges in first time frame using delimiter which is (-1, -1)temp.x = -1;temp.y = -1;Q.push(temp);// Process the grid while there are rotten oranges in the Queuewhile(!Q.empty()){// This flag is used to determine whether even a single fresh// orange gets rotten due to rotten oranges in current time// frame so we can increase the count of the required time.boolflag =false;// Process all the rotten oranges in current time frame.while(!isdelim(Q.front())){temp = Q.front();// Check right adjacent cell that if it can be rottenif(isvalid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1){// if this is the first orange to get rotten, increase// count and set the flag.if(!flag) ans++, flag =true;// Make the orange rottenarr[temp.x+1][temp.y] = 2;// push the adjacent orange to Queuetemp.x++;Q.push(temp);temp.x--;// Move back to current cell}// Check left adjacent cell that if it can be rottenif(isvalid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) {if(!flag) ans++, flag =true;arr[temp.x-1][temp.y] = 2;temp.x--;Q.push(temp);// push this cell to Queuetemp.x++;}// Check top adjacent cell that if it can be rottenif(isvalid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) {if(!flag) ans++, flag =true;arr[temp.x][temp.y+1] = 2;temp.y++;Q.push(temp);// Push this cell to Queuetemp.y--;}// Check bottom adjacent cell if it can be rottenif(isvalid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1) {if(!flag) ans++, flag =true;arr[temp.x][temp.y-1] = 2;temp.y--;Q.push(temp);// push this cell to Queue}Q.pop();}// Pop the delimiterQ.pop();// If oranges were rotten in current frame than separate the// rotten oranges using delimiter for the next frame for processing.if(!Q.empty()) {temp.x = -1;temp.y = -1;Q.push(temp);}// If Queue was empty than no rotten oranges left to process so exit}// Return -1 if all arranges could not rot, otherwise -1.return(checkall(arr))? -1: ans;}// Driver programintmain(){intarr[][C] = { {2, 1, 0, 2, 1},{1, 0, 1, 2, 1},{1, 0, 0, 2, 1}};intans = rotOranges(arr);if(ans == -1)cout <<"All oranges cannot rotn";elsecout <<"Time required for all oranges to rot => "<< ans << endl;return0;}chevron_rightfilter_noneJava
//Java program to find minimum time required to make all//oranges rottenimportjava.util.LinkedList;importjava.util.Queue;publicclassRotOrange{publicfinalstaticintR =3;publicfinalstaticintC =5;// structure for storing coordinates of the cellstaticclassEle{intx =0;inty =0;Ele(intx,inty){this.x = x;this.y = y;}}// function to check whether a cell is valid / invalidstaticbooleanisValid(inti,intj){return(i >=0&& j >=0&& i < R && j < C);}// Function to check whether the cell is delimiter// which is (-1, -1)staticbooleanisDelim(Ele temp){return(temp.x == -1&& temp.y == -1);}// Function to check whether there is still a fresh// orange remainingstaticbooleancheckAll(intarr[][]){for(inti=0; i<R; i++)for(intj=0; j<C; j++)if(arr[i][j] ==1)returntrue;returnfalse;}// This function finds if it is possible to rot all oranges or not.// If possible, then it returns minimum time required to rot all,// otherwise returns -1staticintrotOranges(intarr[][]){// Create a queue of cellsQueue<Ele> Q=newLinkedList<>();Ele temp;intans =0;// Store all the cells having rotten orange in first time framefor(inti=0; i < R; i++)for(intj=0; j < C; j++)if(arr[i][j] ==2)Q.add(newEle(i,j));// Separate these rotten oranges from the oranges which will rotten// due the oranges in first time frame using delimiter which is (-1, -1)Q.add(newEle(-1,-1));// Process the grid while there are rotten oranges in the Queuewhile(!Q.isEmpty()){// This flag is used to determine whether even a single fresh// orange gets rotten due to rotten oranges in the current time// frame so we can increase the count of the required time.booleanflag =false;// Process all the rotten oranges in current time frame.while(!isDelim(Q.peek())){temp = Q.peek();// Check right adjacent cell that if it can be rottenif(isValid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] ==1){if(!flag){// if this is the first orange to get rotten, increase// count and set the flag.ans++;flag =true;}// Make the orange rottenarr[temp.x+1][temp.y] =2;// push the adjacent orange to Queuetemp.x++;Q.add(newEle(temp.x,temp.y));// Move back to current celltemp.x--;}// Check left adjacent cell that if it can be rottenif(isValid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] ==1){if(!flag){ans++;flag =true;}arr[temp.x-1][temp.y] =2;temp.x--;Q.add(newEle(temp.x,temp.y));// push this cell to Queuetemp.x++;}// Check top adjacent cell that if it can be rottenif(isValid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] ==1) {if(!flag){ans++;flag =true;}arr[temp.x][temp.y+1] =2;temp.y++;Q.add(newEle(temp.x,temp.y));// Push this cell to Queuetemp.y--;}// Check bottom adjacent cell if it can be rottenif(isValid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] ==1){if(!flag){ans++;flag =true;}arr[temp.x][temp.y-1] =2;temp.y--;Q.add(newEle(temp.x,temp.y));// push this cell to Queue}Q.remove();}// Pop the delimiterQ.remove();// If oranges were rotten in current frame than separate the// rotten oranges using delimiter for the next frame for processing.if(!Q.isEmpty()){Q.add(newEle(-1,-1));}// If Queue was empty than no rotten oranges left to process so exit}// Return -1 if all arranges could not rot, otherwise -1.sreturn(checkAll(arr))? -1: ans;}// Driver programpublicstaticvoidmain(String[] args){intarr[][] = { {2,1,0,2,1},{1,0,1,2,1},{1,0,0,2,1}};intans = rotOranges(arr);if(ans == -1)System.out.println("All oranges cannot rot");elseSystem.out.println("Time required for all oranges to rot = "+ ans);}}//This code is contributed by Sumit Ghoshchevron_rightfilter_noneC#
// C# program to find minimum time// required to make all oranges rottenusingSystem;usingSystem.Collections.Generic;classGFG{publicconstintR = 3;publicconstintC = 5;// structure for storing// coordinates of the cellpublicclassEle{publicintx = 0;publicinty = 0;publicEle(intx,inty){this.x = x;this.y = y;}}// function to check whether a cell// is valid / invalidpublicstaticboolisValid(inti,intj){return(i >= 0 && j >= 0 &&i < R && j < C);}// Function to check whether the cell// is delimiter which is (-1, -1)publicstaticboolisDelim(Ele temp){return(temp.x == -1 && temp.y == -1);}// Function to check whether there// is still a fresh orange remainingpublicstaticboolcheckAll(int[][] arr){for(inti = 0; i < R; i++){for(intj = 0; j < C; j++){if(arr[i][j] == 1){returntrue;}}}returnfalse;}// This function finds if it is possible// to rot all oranges or not. If possible,// then it returns minimum time required// to rot all, otherwise returns -1publicstaticintrotOranges(int[][] arr){// Create a queue of cellsLinkedList<Ele> Q =newLinkedList<Ele>();Ele temp;intans = 0;// Store all the cells having rotten// orange in first time framefor(inti = 0; i < R; i++){for(intj = 0; j < C; j++){if(arr[i][j] == 2){Q.AddLast(newEle(i, j));}}}// Separate these rotten oranges from// the oranges which will rotten// due the oranges in first time frame// using delimiter which is (-1, -1)Q.AddLast(newEle(-1,-1));// Process the grid while there are// rotten oranges in the Queuewhile(Q.Count > 0){// This flag is used to determine// whether even a single fresh// orange gets rotten due to rotten// oranges in current time frame so// we can increase the count of the// required time.boolflag =false;// Process all the rotten oranges// in current time frame.while(!isDelim(Q.First.Value)){temp = Q.First.Value;// Check right adjacent cell that// if it can be rottenif(isValid(temp.x + 1, temp.y) &&arr[temp.x + 1][temp.y] == 1){if(!flag){// if this is the first orange// to get rotten, increase// count and set the flag.ans++;flag =true;}// Make the orange rottenarr[temp.x + 1][temp.y] = 2;// push the adjacent orange to Queuetemp.x++;Q.AddLast(newEle(temp.x,temp.y));// Move back to current celltemp.x--;}// Check left adjacent cell that// if it can be rottenif(isValid(temp.x - 1, temp.y) &&arr[temp.x - 1][temp.y] == 1){if(!flag){ans++;flag =true;}arr[temp.x - 1][temp.y] = 2;temp.x--;// push this cell to QueueQ.AddLast(newEle(temp.x,temp.y));temp.x++;}// Check top adjacent cell that// if it can be rottenif(isValid(temp.x, temp.y + 1) &&arr[temp.x][temp.y + 1] == 1){if(!flag){ans++;flag =true;}arr[temp.x][temp.y + 1] = 2;temp.y++;// Push this cell to QueueQ.AddLast(newEle(temp.x,temp.y));temp.y--;}// Check bottom adjacent cell// if it can be rottenif(isValid(temp.x, temp.y - 1) &&arr[temp.x][temp.y - 1] == 1){if(!flag){ans++;flag =true;}arr[temp.x][temp.y - 1] = 2;temp.y--;// push this cell to QueueQ.AddLast(newEle(temp.x,temp.y));}Q.RemoveFirst();}// Pop the delimiterQ.RemoveFirst();// If oranges were rotten in current// frame than separate the rotten// oranges using delimiter for the// next frame for processing.if(Q.Count > 0){Q.AddLast(newEle(-1,-1));}// If Queue was empty than no rotten// oranges left to process so exit}// Return -1 if all arranges could// not rot, otherwise -1.sreturn(checkAll(arr)) ? -1: ans;}// Driver CodepublicstaticvoidMain(string[] args){int[][] arr =newint[][]{newint[] {2, 1, 0, 2, 1},newint[] {1, 0, 1, 2, 1},newint[] {1, 0, 0, 2, 1}};intans = rotOranges(arr);if(ans == -1){Console.WriteLine("All oranges cannot rot");}else{Console.WriteLine("Time required for all "+"oranges to rot => "+ ans);}}}// This code is contributed by Shrikant13chevron_rightfilter_none
Output:Time required for all oranges to rot => 2
-
Complexity Analysis:
- Time Complexity: O( R *C).
Each element of the matrix can be inserted into the queue only once so the upperbound of iteration is O(R*C), i.e. the number of elements. So time complexity is O(R *C). - Space Complexity: O(R*C).
To store the elements in a queue O(R*C) space is needed.
- Time Complexity: O( R *C).
Thanks to Gaurav Ahirwar for suggesting the above solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimum time required to rot all oranges | Dynamic Programming
- Minimum time required to fill the entire matrix with 1's
- Minimum steps required to reach the end of a matrix | Set 2
- Minimum changes required to make each path in a matrix palindrome
- Find minimum steps required to reach the end of a matrix | Set - 1
- Minimum number of swaps required to sort an array
- Find minimum steps required to reach the end of a matrix | Set 2
- Minimum edges required to add to make Euler Circuit
- Minimum number of pairs required to make two strings same
- Minimum operations required to set all elements of binary matrix
- Minimum sprinklers required to water a rectangular park
- Minimum number of colors required to color a graph
- Minimum Initial Energy Required To Cross Street
- Minimum Number of Platforms Required for a Railway/Bus Station
- Minimum queens required to cover all the squares of a chess board
- Minimum operations required to make each row and column of matrix equals
- Minimum flip required to make Binary Matrix symmetric
- Minimum number of points required to cover all blocks of a 2-D grid
- Minimum operations required to make every element greater than or equal to K
- Minimum colors required such that edges forming cycle do not have same color

