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 oranges which are its neighbours (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: 2
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: -1
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 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 that were rotten in the last round.
Follow the steps below to solve the problem:
- Create a variable no = 2 and changed = false.
- Run a loop until there is no cell of the matrix which is changed in an 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 element’s value is equal to 1, i.e. not rotten, and update changed to true.
- Traverse the matrix and check if there is any cell that is 1.
- If 1 is present return -1
- Else return no – 2.
Below is the implementation of the above approach.
C++14
#include <bits/stdc++.h>
using namespace std;
const int R = 3;
const int C = 5;
bool issafe( int i, int j)
{
if (i >= 0 && i < R && j >= 0 && j < C)
return true ;
return false ;
}
int rotOranges( int v[R][C])
{
bool changed = false ;
int no = 2;
while ( true ) {
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; 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 (!changed)
break ;
changed = false ;
no++;
}
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++) {
if (v[i][j] == 1)
return -1;
}
}
return no - 2;
}
int main()
{
int v[R][C] = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
cout << "Max time incurred: " << rotOranges(v);
return 0;
}
|
Java
class GFG {
static int R = 3 ;
static int C = 5 ;
static boolean issafe( int i, int j)
{
if (i >= 0 && i < R && j >= 0 && j < C)
return true ;
return false ;
}
static int rotOranges( int v[][])
{
boolean changed = false ;
int no = 2 ;
while ( true ) {
for ( int i = 0 ; i < R; i++) {
for ( int j = 0 ; j < C; 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 (!changed)
break ;
changed = false ;
no++;
}
for ( int i = 0 ; i < R; i++) {
for ( int j = 0 ; j < C; j++) {
if (v[i][j] == 1 )
return - 1 ;
}
}
return no - 2 ;
}
public static void main(String[] args)
{
int v[][] = { { 2 , 1 , 0 , 2 , 1 },
{ 1 , 0 , 1 , 2 , 1 },
{ 1 , 0 , 0 , 2 , 1 } };
System.out.println( "Max time incurred: "
+ rotOranges(v));
}
}
|
Python3
R = 3
C = 5
def issafe(i, j):
if (i > = 0 and i < R and
j > = 0 and j < C):
return True
return False
def rotOranges(v):
changed = False
no = 2
while ( True ):
for i in range (R):
for j in range (C):
if (v[i][j] = = no):
if (issafe(i + 1 , j) and
v[i + 1 ][j] = = 1 ):
v[i + 1 ][j] = v[i][j] + 1
changed = True
if (issafe(i, j + 1 ) and
v[i][j + 1 ] = = 1 ):
v[i][j + 1 ] = v[i][j] + 1
changed = True
if (issafe(i - 1 , j) and
v[i - 1 ][j] = = 1 ):
v[i - 1 ][j] = v[i][j] + 1
changed = True
if (issafe(i, j - 1 ) and
v[i][j - 1 ] = = 1 ):
v[i][j - 1 ] = v[i][j] + 1
changed = True
if ( not changed):
break
changed = False
no + = 1
for i in range (R):
for j in range (C):
if (v[i][j] = = 1 ):
return - 1
return no - 2
if __name__ = = "__main__" :
v = [[ 2 , 1 , 0 , 2 , 1 ],
[ 1 , 0 , 1 , 2 , 1 ],
[ 1 , 0 , 0 , 2 , 1 ]]
print ( "Max time incurred: " ,
rotOranges(v))
|
C#
using System;
class GFG {
static int R = 3;
static int C = 5;
static bool issafe( int i, int j)
{
if (i >= 0 && i < R && j >= 0 && j < C)
return true ;
return false ;
}
static int rotOranges( int [, ] v)
{
bool changed = false ;
int no = 2;
while ( true ) {
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; 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 (!changed)
break ;
changed = false ;
no++;
}
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++) {
if (v[i, j] == 1)
return -1;
}
}
return no - 2;
}
static void Main()
{
int [, ] v = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
Console.Write( "Max time incurred: "
+ rotOranges(v));
}
}
|
Javascript
<script>
let R = 3;
let C = 5;
function issafe(i, j)
{
if (i >= 0 && i < R && j >= 0 && j < C)
return true ;
return false ;
}
function rotOranges(v)
{
let changed = false ;
let no = 2;
while ( true ) {
for (let i = 0; i < R; i++) {
for (let j = 0; j < C; 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 (!changed)
break ;
changed = false ;
no++;
}
for (let i = 0; i < R; i++) {
for (let j = 0; j < C; j++) {
if (v[i][j] == 1)
return -1;
}
}
return no - 2;
}
let v = [ [ 2, 1, 0, 2, 1 ],
[ 1, 0, 1, 2, 1 ],
[ 1, 0, 0, 2, 1 ] ];
document.write( "Max time incurred: " + rotOranges(v));
</script>
|
OutputMax time incurred: 2
Time Complexity: O((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)/2 times.
- So time complexity is O((R * C) * (R *C)).
Auxiliary Space: O(1), No extra space is required.
Minimum time required to rot all oranges using Breadth First Search:
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 a 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 time can be reduced by using this efficient approach of BFS.
Follow the steps below to solve the problem:
- Create an empty queue Q.
- Find all rotten oranges and enqueue them to Q. Also, enqueue a delimiter to indicate the beginning of the next time frame.
- Run a loop While Q is not empty and do the following while the delimiter in Q is not reached
- Dequeue an orange from the queue, and 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.
- Return the last time frame.
Illustration:

Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
#define R 3
#define C 5
using namespace std;
int rotOranges(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 };
int vis[n][m];
queue<pair<pair< int , int >, int > > q;
int cntfresh = 0;
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;
}
if (grid[i][j] == 1)
cntfresh++;
}
}
int cnt = 0, tm = 0;
while (!q.empty()) {
int row = q.front().first.first;
int col = q.front().first.second;
int t = q.front().second;
q.pop();
tm = max( tm , t);
for ( int i = 0; i < 4; i++) {
int nrow = row + delrow[i];
int ncol = col + delcol[i];
if (nrow >= 0 && nrow < n && ncol >= 0
&& ncol < m && grid[nrow][ncol] == 1
&& vis[nrow][ncol] != 2) {
vis[nrow][ncol] = 2;
q.push({ { nrow, ncol },
t + 1 });
cnt++;
}
}
}
return (cnt == cntfresh) ? tm : -1;
}
int main()
{
vector<vector< int > > arr
= { { 0, 1, 2 }, { 0, 1, 2 }, { 2, 1, 1 } };
int ans = rotOranges(arr);
if (ans == -1)
cout << "All oranges cannot rotn" ;
else
cout << "Time required for all oranges to rot => "
<< ans << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class RotOrange {
public final static int R = 3 ;
public final static int C = 5 ;
static class Ele {
int x = 0 ;
int y = 0 ;
Ele( int x, int y)
{
this .x = x;
this .y = y;
}
}
static boolean isValid( int i, int j)
{
return (i >= 0 && j >= 0 && i < R && j < C);
}
static boolean isDelim(Ele temp)
{
return (temp.x == - 1 && temp.y == - 1 );
}
static boolean checkAll( int arr[][])
{
for ( int i = 0 ; i < R; i++)
for ( int j = 0 ; j < C; j++)
if (arr[i][j] == 1 )
return true ;
return false ;
}
static int rotOranges( int arr[][])
{
Queue<Ele> Q = new LinkedList<>();
Ele temp;
int ans = 0 ;
for ( int i = 0 ; i < R; i++)
for ( int j = 0 ; j < C; j++)
if (arr[i][j] == 2 )
Q.add( new Ele(i, j));
Q.add( new Ele(- 1 , - 1 ));
while (!Q.isEmpty()) {
boolean flag = false ;
while (!isDelim(Q.peek())) {
temp = Q.peek();
if (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( new Ele(temp.x, temp.y));
temp.x--;
}
if (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( new Ele(
temp.x,
temp.y));
temp.x++;
}
if (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( new Ele(
temp.x,
temp.y));
temp.y--;
}
if (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( new Ele(
temp.x,
temp.y));
}
Q.remove();
}
Q.remove();
if (!Q.isEmpty()) {
Q.add( new Ele(- 1 , - 1 ));
}
}
return (checkAll(arr)) ? - 1 : ans;
}
public static void main(String[] args)
{
int arr[][] = { { 2 , 1 , 0 , 2 , 1 },
{ 1 , 0 , 1 , 2 , 1 },
{ 1 , 0 , 0 , 2 , 1 } };
int ans = rotOranges(arr);
if (ans == - 1 )
System.out.println( "All oranges cannot rot" );
else
System.out.println(
"Time required for all oranges to rot => "
+ ans);
}
}
|
Python3
from collections import deque
def isvalid(i, j):
return (i > = 0 and j > = 0 and i < 3 and j < 5 )
def isdelim(temp):
return (temp[ 0 ] = = - 1 and temp[ 1 ] = = - 1 )
def checkall(arr):
for i in range ( 3 ):
for j in range ( 5 ):
if (arr[i][j] = = 1 ):
return True
return False
def rotOranges(arr):
Q = deque()
temp = [ 0 , 0 ]
ans = 1
for i in range ( 3 ):
for j in range ( 5 ):
if (arr[i][j] = = 2 ):
temp[ 0 ] = i
temp[ 1 ] = j
Q.append([i, j])
temp[ 0 ] = - 1
temp[ 1 ] = - 1
Q.append([ - 1 , - 1 ])
while False :
flag = False
print ( len (Q))
while not isdelim(Q[ 0 ]):
temp = Q[ 0 ]
print ( len (Q))
if (isvalid(temp[ 0 ] + 1 , temp[ 1 ]) and arr[temp[ 0 ] + 1 ][temp[ 1 ]] = = 1 ):
if ( not flag):
ans, flag = ans + 1 , True
arr[temp[ 0 ] + 1 ][temp[ 1 ]] = 2
temp[ 0 ] + = 1
Q.append(temp)
temp[ 0 ] - = 1
if (isvalid(temp[ 0 ] - 1 , temp[ 1 ]) and arr[temp[ 0 ] - 1 ][temp[ 1 ]] = = 1 ):
if ( not flag):
ans, flag = ans + 1 , True
arr[temp[ 0 ] - 1 ][temp[ 1 ]] = 2
temp[ 0 ] - = 1
Q.append(temp)
temp[ 0 ] + = 1
if (isvalid(temp[ 0 ], temp[ 1 ] + 1 ) and arr[temp[ 0 ]][temp[ 1 ] + 1 ] = = 1 ):
if ( not flag):
ans, flag = ans + 1 , True
arr[temp[ 0 ]][temp[ 1 ] + 1 ] = 2
temp[ 1 ] + = 1
Q.append(temp)
temp[ 1 ] - = 1
if (isvalid(temp[ 0 ], temp[ 1 ] - 1 ) and arr[temp[ 0 ]][temp[ 1 ] - 1 ] = = 1 ):
if ( not flag):
ans, flag = ans + 1 , True
arr[temp[ 0 ]][temp[ 1 ] - 1 ] = 2
temp[ 1 ] - = 1
Q.append(temp)
Q.popleft()
Q.popleft()
if ( len (Q) = = 0 ):
temp[ 0 ] = - 1
temp[ 1 ] = - 1
Q.append(temp)
return ans + 1 if (checkall(arr)) else - 1
if __name__ = = '__main__' :
arr = [[ 2 , 1 , 0 , 2 , 1 ],
[ 1 , 0 , 1 , 2 , 1 ],
[ 1 , 0 , 0 , 2 , 1 ]]
ans = rotOranges(arr)
if (ans = = - 1 ):
print ( "All oranges cannot rotn" )
else :
print ( "Time required for all oranges to rot => " , ans)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public const int R = 3;
public const int C = 5;
public class Ele {
public int x = 0;
public int y = 0;
public Ele( int x, int y)
{
this .x = x;
this .y = y;
}
}
public static bool isValid( int i, int j)
{
return (i >= 0 && j >= 0 && i < R && j < C);
}
public static bool isDelim(Ele temp)
{
return (temp.x == -1 && temp.y == -1);
}
public static bool checkAll( int [][] arr)
{
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++) {
if (arr[i][j] == 1) {
return true ;
}
}
}
return false ;
}
public static int rotOranges( int [][] arr)
{
LinkedList<Ele> Q = new LinkedList<Ele>();
Ele temp;
int ans = 0;
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++) {
if (arr[i][j] == 2) {
Q.AddLast( new Ele(i, j));
}
}
}
Q.AddLast( new Ele(-1, -1));
while (Q.Count > 0) {
bool flag = false ;
while (!isDelim(Q.First.Value)) {
temp = Q.First.Value;
if (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.AddLast( new Ele(temp.x, temp.y));
temp.x--;
}
if (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.AddLast( new Ele(temp.x, temp.y));
temp.x++;
}
if (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.AddLast( new Ele(temp.x, temp.y));
temp.y--;
}
if (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.AddLast( new Ele(temp.x, temp.y));
}
Q.RemoveFirst();
}
Q.RemoveFirst();
if (Q.Count > 0) {
Q.AddLast( new Ele(-1, -1));
}
}
return (checkAll(arr)) ? -1 : ans;
}
public static void Main( string [] args)
{
int [][] arr
= new int [][] { new int [] { 2, 1, 0, 2, 1 },
new int [] { 1, 0, 1, 2, 1 },
new int [] { 1, 0, 0, 2, 1 } };
int ans = rotOranges(arr);
if (ans == -1) {
Console.WriteLine( "All oranges cannot rot" );
}
else {
Console.WriteLine( "Time required for all "
+ "oranges to rot => " + ans);
}
}
}
|
Javascript
function isvalid(i, j)
{
return (i >= 0 && j >= 0 && i < 3 && j < 5)
}
function isdelim(temp)
{
return (temp[0] == -1 && temp[1] == -1)
}
function checkall(arr)
{
for ( var i = 0; i < 3; i++)
for ( var j = 0; j < 5; j++)
if (arr[i][j] == 1)
return true
return false
}
function rotOranges(arr)
{
let Q = []
let temp = [0, 0]
let ans = 1
for ( var i = 0; i < 3; i++)
{
for ( var j = 0; j < 5; j++)
{
if (arr[i][j] == 2)
{
temp[0] = i
temp[1] = j
Q.push([i, j])
}
}
}
temp[0] = -1
temp[1] = -1
Q.push([-1, -1])
while ( false )
{
flag = false
console.log(Q.length)
while (!isdelim(Q[0]))
{
temp = Q[0]
console.log(Q.length)
if (isvalid(temp[0] + 1, temp[1]) && arr[temp[0] + 1][temp[1]] == 1)
{
if (!flag)
{
ans = ans + 1
flag = true
}
arr[temp[0] + 1][temp[1]] = 2
temp[0] += 1
Q.push(temp)
temp[0] -= 1
}
if (isvalid(temp[0] - 1, temp[1]) && arr[temp[0] - 1][temp[1]] == 1)
{
if (!flag)
{
ans = ans + 1
flag = true
}
arr[temp[0] - 1][temp[1]] = 2
temp[0] -= 1
Q.push(temp)
temp[0] += 1
}
if (isvalid(temp[0], temp[1] + 1) && arr[temp[0]][temp[1] + 1] == 1)
{
if (!flag)
{
ans++;
flag = true ;
}
arr[temp[0]][temp[1] + 1] = 2
temp[1] += 1
Q.push(temp)
temp[1] -= 1
}
if (isvalid(temp[0], temp[1] - 1) && arr[temp[0]][temp[1] - 1] == 1)
{
if (!flag)
{
ans ++;
flag = true ;
}
arr[temp[0]][temp[1] - 1] = 2
temp[1] -= 1
Q.push(temp)
}
Q.shift()
}
Q.shift()
if (Q.length == 0)
{
temp[0] = -1
temp[1] = -1
Q.push(temp)
}
}
if (checkall(arr))
return ans + 1
return -1
}
let arr = [[2, 1, 0, 2, 1],
[1, 0, 1, 2, 1],
[1, 0, 0, 2, 1]]
let ans = rotOranges(arr)
if (ans == -1)
console.log( "All oranges cannot rotn" )
else
console.log( "Time required for all oranges to rot => " , ans)
|
OutputTime required for all oranges to rot => 2
Time Complexity: O( R *C), Each element of the matrix can be inserted into the queue only once so the upper bound of iteration is O(R*C)
Auxiliary Space: O(R*C), To store the elements in a queue.
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