Rotten Oranges – Minimum Time to Rot All
Last Updated :
17 Sep, 2024
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
The task is to 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 neighbors (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:
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. For the first round we consider all initially rotten oranges.
Below is the implementation of the above approach.
C++
#include <iostream>
#include <vector>
using namespace std;
// Check if i, j is within the array limits
// of row and column
bool isSafe(int i, int j, int rows, int cols) {
return (i >= 0 && i < rows && j >= 0 && j < cols);
}
int rotOranges(vector<vector<int>>& v) {
int rows = v.size();
int cols = v[0].size();
bool changed = false;
int no = 2;
while (true) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; 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, rows, cols) && v[i + 1][j] == 1) {
v[i + 1][j] = v[i][j] + 1;
changed = true;
}
if (isSafe(i, j + 1, rows, cols) && v[i][j + 1] == 1) {
v[i][j + 1] = v[i][j] + 1;
changed = true;
}
if (isSafe(i - 1, j, rows, cols) && v[i - 1][j] == 1) {
v[i - 1][j] = v[i][j] + 1;
changed = true;
}
if (isSafe(i, j - 1, rows, cols) && v[i][j - 1] == 1) {
v[i][j - 1] = v[i][j] + 1;
changed = true;
}
}
}
}
// if no oranges were rotten in
// this round, break the loop
if (!changed) break;
changed = false;
no++;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// if any orange is found to
// be not rotten, return -1
if (v[i][j] == 1) return -1;
}
}
// Because initial value for
// a rotten orange was 2
return no - 2;
}
// Driver function
int main() {
vector<vector<int>> v = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
cout << "Max time incurred: "
<< rotOranges(v) << endl;
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#define R 3
#define C 5
// Check if i, j is within the array
// limits of row and column
bool isSafe(int i, int j) {
return (i >= 0 && i < R && j >= 0 && j < C);
}
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++) {
// 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 oranges were rotten
// in this round, break the loop
if (!changed) break;
changed = false;
no++;
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
// if any orange is found to
// be not rotten, return -1
if (v[i][j] == 1) return -1;
}
}
// Because initial value for a rotten orange was 2
return no - 2;
}
// Driver function
int main() {
int v[R][C] = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
printf("Max time incurred: %d\n", rotOranges(v));
return 0;
}
Java
import java.util.*;
class GfG {
// Check if i, j is within the array limits of rows and cols
public static boolean isSafe(int i, int j, int rows, int cols) {
return (i >= 0 && i < rows && j >= 0 && j < cols);
}
public static int rotOranges(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
boolean changed = false;
int no = 2;
while (true) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Rot all other oranges present at (i+1, j), (i, j-1), (i, j+1), (i-1, j)
if (grid[i][j] == no) {
if (isSafe(i + 1, j, rows, cols) && grid[i + 1][j] == 1) {
grid[i + 1][j] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i, j + 1, rows, cols) && grid[i][j + 1] == 1) {
grid[i][j + 1] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i - 1, j, rows, cols) && grid[i - 1][j] == 1) {
grid[i - 1][j] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i, j - 1, rows, cols) && grid[i][j - 1] == 1) {
grid[i][j - 1] = grid[i][j] + 1;
changed = true;
}
}
}
}
// If no oranges were rotten in this round, break the loop
if (!changed) break;
changed = false;
no++;
}
// Check if any fresh orange is still left
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 1) return -1;
}
}
// Subtract 2 as the initial value for a rotten orange was 2
return no - 2;
}
// Driver method
public static void main(String[] args) {
int[][] grid = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
System.out.println("Max time incurred: " + rotOranges(grid));
}
}
Python
# Check if i, j is within the array limits of rows and cols
def is_safe(i, j, rows, cols):
return (i >= 0 and i < rows and j >= 0 and j < cols)
def rot_oranges(grid):
rows = len(grid)
cols = len(grid[0])
changed = False
no = 2
while True:
for i in range(rows):
for j in range(cols):
# Rot all other oranges present at (i+1, j), (i, j-1),
# (i, j+1), (i-1, j)
if grid[i][j] == no:
if is_safe(i + 1, j, rows, cols) and grid[i + 1][j] == 1:
grid[i + 1][j] = grid[i][j] + 1
changed = True
if is_safe(i, j + 1, rows, cols) and grid[i][j + 1] == 1:
grid[i][j + 1] = grid[i][j] + 1
changed = True
if is_safe(i - 1, j, rows, cols) and grid[i - 1][j] == 1:
grid[i - 1][j] = grid[i][j] + 1
changed = True
if is_safe(i, j - 1, rows, cols) and grid[i][j - 1] == 1:
grid[i][j - 1] = grid[i][j] + 1
changed = True
# If no oranges were rotten in this round, break the loop
if not changed:
break
changed = False
no += 1
# Check if any fresh orange is still left
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
return -1
# Subtract 2 as the initial value
# for a rotten orange was 2
return no - 2
# Driver method
if __name__ == "__main__":
grid = [[2, 1, 0, 2, 1],
[1, 0, 1, 2, 1],
[1, 0, 0, 2, 1]]
print("Max time incurred:", rot_oranges(grid))
C#
using System;
class GfG
{
// Check if i, j is within the array limits of rows and cols
public static bool IsSafe(int i, int j, int rows, int cols)
{
return (i >= 0 && i < rows && j >= 0 && j < cols);
}
public static int RotOranges(int[,] grid)
{
int rows = grid.GetLength(0);
int cols = grid.GetLength(1);
bool changed = false;
int no = 2;
while (true)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// Rot all other oranges present at (i+1, j), (i, j-1),
// (i, j+1), (i-1, j)
if (grid[i, j] == no)
{
if (IsSafe(i + 1, j, rows, cols) && grid[i + 1, j] == 1)
{
grid[i + 1, j] = grid[i, j] + 1;
changed = true;
}
if (IsSafe(i, j + 1, rows, cols) && grid[i, j + 1] == 1)
{
grid[i, j + 1] = grid[i, j] + 1;
changed = true;
}
if (IsSafe(i - 1, j, rows, cols) && grid[i - 1, j] == 1)
{
grid[i - 1, j] = grid[i, j] + 1;
changed = true;
}
if (IsSafe(i, j - 1, rows, cols) && grid[i, j - 1] == 1)
{
grid[i, j - 1] = grid[i, j] + 1;
changed = true;
}
}
}
}
// If no oranges were rotten in this round, break the loop
if (!changed)
break;
changed = false;
no++;
}
// Check if any fresh orange is still left
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (grid[i, j] == 1)
return -1;
}
}
// Subtract 2 as the initial value for a rotten orange was 2
return no - 2;
}
public static void Main()
{
int[,] grid = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 1 } };
Console.WriteLine("Max time incurred: " + RotOranges(grid));
}
}
JavaScript
// Check if i, j is within the array limits of rows and cols
function isSafe(i, j, rows, cols) {
return i >= 0 && i < rows && j >= 0 && j < cols;
}
function rotOranges(grid) {
let rows = grid.length;
let cols = grid[0].length;
let changed = false;
let no = 2;
while (true) {
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
// Rot all other oranges present at (i+1, j),
// (i, j-1), (i, j+1), (i-1, j)
if (grid[i][j] === no) {
if (isSafe(i + 1, j, rows, cols) && grid[i + 1][j] === 1) {
grid[i + 1][j] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i, j + 1, rows, cols) && grid[i][j + 1] === 1) {
grid[i][j + 1] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i - 1, j, rows, cols) && grid[i - 1][j] === 1) {
grid[i - 1][j] = grid[i][j] + 1;
changed = true;
}
if (isSafe(i, j - 1, rows, cols) && grid[i][j - 1] === 1) {
grid[i][j - 1] = grid[i][j] + 1;
changed = true;
}
}
}
}
// If no oranges were rotten in this round, break the loop
if (!changed) break;
changed = false;
no++;
}
// Check if any fresh orange is still left
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (grid[i][j] === 1) return -1;
}
}
// Subtract 2 as the initial value for a rotten orange was 2
return no - 2;
}
// Driver code
let grid = [
[2, 1, 0, 2, 1],
[1, 0, 1, 2, 1],
[1, 0, 0, 2, 1]
];
console.log("Max time incurred:", rotOranges(grid));
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.
The idea is to use Breadth First Search. In the previous approach, the idea was based on BFS but the implementation was poor and inefficient. Here we use queue data structure.
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:
Step 0: At time t=0, insert all the rotten oranges into the queue, these will act as source for multisource BFS.

Minimum time required to rotten all oranges
Step 1: At time t=1, all the fresh oranges which are adjacent to rotten oranges all made rotten and inserted into the queue.

Minimum time required to rotten all oranges
Step 2: At time t=2, the last fresh orange is made rotten and inserted into the queue.

Minimum time required to rotten all oranges
Step 3: After the last fresh orange is made rotten, no new orange will be added to queue and queue will become empty. Since the last fresh orange became rotten at time t=2, minimum time required to rot all oranges will be 2.

Minimum time required to rotten all oranges
Below is the implementation of the above approach.
C++
// C++ program to find minimum time required to make all
// oranges rotten
#include <bits/stdc++.h>
using namespace std;
// This function first finds if it is possible to rot
// all oranges or not. If possible, then it returns
// minimum time required to rot all, otherwise returns -1
int rotOranges(vector<vector<int> >& grid)
{
int n = grid.size();
int m = grid[0].size();
// delrow and delcol are used to traverse in
// up,right,bottom and left respectively.
int delrow[] = { -1, 0, 1, 0 };
int delcol[] = { 0, 1, 0, -1 };
// visited matrix to keep track of the visited cell.
int vis[n][m];
// queue stores rowIndex,colIndex and time taken to rot
// respectively.
queue<pair<pair<int, int>, int> > q;
// counter to keep track of fresh cells.
int cntfresh = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// already rotten hence 0 time to rot.
// and mark as visited
if (grid[i][j] == 2) {
q.push({ { i, j }, 0});
vis[i][j] = 2;
}
else {
vis[i][j] = 0; // unvisited
}
// Increment count for fresh oranges.
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);
// checking for adjacent nodes in 4 directions.
for (int i = 0; i < 4; i++) {
int nrow = row + delrow[i];
int ncol = col + delcol[i];
// checking the validity of a node and also
// vis[nrow][ncol] !=2
if (nrow >= 0 && nrow < n && ncol >= 0
&& ncol < m && grid[nrow][ncol] == 1
&& vis[nrow][ncol] != 2) {
// adj orange is rotten
vis[nrow][ncol] = 2;
// incrementing time for that orange by 1
q.push({ { nrow, ncol }, t + 1 });
cnt++;
}
}
}
return (cnt == cntfresh) ? tm : -1;
}
// Driver program
int main()
{
vector<vector<int> > arr = { { 2, 1, 0, 2, 1 },
{ 1, 0, 1, 2, 1 },
{ 1, 0, 0, 2, 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;
class GfG {
// 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 -1
public static int rotOranges(int[][] grid) {
int n = grid.length; // row size
int m = grid[0].length; // column size
// delRow and delCol are used to traverse in
// up, right, bottom, and left respectively.
int[] delRow = {-1, 0, 1, 0};
int[] delCol = {0, 1, 0, -1};
// visited matrix to keep track of the visited cell.
int[][] vis = new int[n][m];
// queue stores rowIndex, colIndex, and time taken to rot respectively.
Queue<int[]> q = new LinkedList<>();
// counter to keep track of fresh cells.
int freshCount = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// already rotten hence 0 time to rot and mark as visited
if (grid[i][j] == 2) {
q.add(new int[]{i, j, 0});
vis[i][j] = 2;
} else {
vis[i][j] = 0; // unvisited
}
// Increment count for fresh oranges.
if (grid[i][j] == 1) {
freshCount++;
}
}
}
int cnt = 0, tm = 0;
while (!q.isEmpty()) {
int[] curr = q.poll();
int row = curr[0];
int col = curr[1];
int t = curr[2];
tm = Math.max(tm, t);
// checking for adjacent nodes in 4 directions.
for (int i = 0; i < 4; i++) {
int newRow = row + delRow[i];
int newCol = col + delCol[i];
// checking the validity of a node and if it is not visited yet
if (newRow >= 0 && newRow < n && newCol >= 0
&& newCol < m && grid[newRow][newCol] == 1
&& vis[newRow][newCol] != 2) {
// adjacent orange is rotten
vis[newRow][newCol] = 2;
// incrementing time for that orange by 1
q.add(new int[]{newRow, newCol, t + 1});
cnt++;
}
}
}
// return time if all fresh oranges are rotten, otherwise return -1
return (cnt == freshCount) ? tm : -1;
}
// Driver program
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);
}
}
Python
from collections import deque
# 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 -1
def rotOranges(grid):
n = len(grid) # row size
m = len(grid[0]) # column size
# delRow and delCol are used to traverse in
# up, right, bottom, and left respectively.
delRow = [-1, 0, 1, 0]
delCol = [0, 1, 0, -1]
# visited matrix to keep track of the visited cell.
vis = [[0 for _ in range(m)] for _ in range(n)]
# queue stores rowIndex, colIndex, and time taken to rot respectively.
q = deque()
# counter to keep track of fresh cells.
freshCount = 0
for i in range(n):
for j in range(m):
# already rotten hence 0 time to
# rot and mark as visited
if grid[i][j] == 2:
q.append((i, j, 0))
vis[i][j] = 2
else:
vis[i][j] = 0 # unvisited
# Increment count for fresh oranges.
if grid[i][j] == 1:
freshCount += 1
cnt = 0
tm = 0
while q:
row, col, t = q.popleft()
tm = max(tm, t)
# checking for adjacent nodes in 4 directions.
for i in range(4):
newRow = row + delRow[i]
newCol = col + delCol[i]
# checking the validity of a node and if it is not visited yet
if 0 <= newRow < n and 0 <= newCol < m and \
grid[newRow][newCol] == 1 and vis[newRow][newCol] != 2:
# adjacent orange is rotten
vis[newRow][newCol] = 2
# incrementing time for that orange by 1
q.append((newRow, newCol, t + 1))
cnt += 1
# return time if all fresh oranges are rotten, otherwise return -1
return tm if cnt == freshCount else -1
# Driver program
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 rot")
else:
print("Time required for all oranges to rot: ", ans)
C#
using System;
using System.Collections.Generic;
class GfG {
// 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 -1
public static int RotOranges(int[,] grid) {
int n = grid.GetLength(0); // row size
int m = grid.GetLength(1); // column size
// delRow and delCol are used to traverse in
// up, right, bottom, and left respectively.
int[] delRow = { -1, 0, 1, 0 };
int[] delCol = { 0, 1, 0, -1 };
// visited matrix to keep track of the visited cell.
int[,] vis = new int[n, m];
// queue stores rowIndex, colIndex, and time taken to rot respectively.
Queue<Tuple<int, int, int>> q = new Queue<Tuple<int, int, int>>();
// counter to keep track of fresh cells.
int freshCount = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// already rotten hence 0 time to rot and mark as visited
if (grid[i, j] == 2) {
q.Enqueue(new Tuple<int, int, int>(i, j, 0));
vis[i, j] = 2;
} else {
vis[i, j] = 0; // unvisited
}
// Increment count for fresh oranges.
if (grid[i, j] == 1)
freshCount++;
}
}
int cnt = 0, tm = 0;
while (q.Count > 0) {
var current = q.Dequeue();
int row = current.Item1;
int col = current.Item2;
int t = current.Item3;
tm = Math.Max(tm, t);
// checking for adjacent nodes in 4 directions.
for (int i = 0; i < 4; i++) {
int newRow = row + delRow[i];
int newCol = col + delCol[i];
// checking the validity of a node and if it is not visited yet
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m
&& grid[newRow, newCol] == 1 && vis[newRow, newCol] != 2) {
// adjacent orange is rotten
vis[newRow, newCol] = 2;
// incrementing time for that orange by 1
q.Enqueue(new Tuple<int, int, int>(newRow, newCol, t + 1));
cnt++;
}
}
}
// return time if all fresh oranges are rotten, otherwise return -1
return (cnt == freshCount) ? tm : -1;
JavaScript
// 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 -1
function rotOranges(grid) {
let n = grid.length; // row size
let m = grid[0].length; // column size
// delRow and delCol are used to traverse in
// up, right, bottom, and left respectively.
const delRow = [-1, 0, 1, 0];
const delCol = [0, 1, 0, -1];
// visited matrix to keep track of the visited cell.
const vis = Array.from({ length: n }, () => Array(m).fill(0));
// queue stores rowIndex, colIndex, and time taken to rot respectively.
const q = [];
// counter to keep track of fresh cells.
let freshCount = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// already rotten hence 0 time to rot and mark as visited
if (grid[i][j] === 2) {
q.push([i, j, 0]);
vis[i][j] = 2;
} else {
vis[i][j] = 0; // unvisited
}
// Increment count for fresh oranges.
if (grid[i][j] === 1) {
freshCount++;
}
}
}
let cnt = 0, tm = 0;
while (q.length > 0) {
const [row, col, t] = q.shift();
tm = Math.max(tm, t);
// checking for adjacent nodes in 4 directions.
for (let i = 0; i < 4; i++) {
let newRow = row + delRow[i];
let newCol = col + delCol[i];
// checking the validity of a node and if it is not visited yet
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m
&& grid[newRow][newCol] === 1 && vis[newRow][newCol] !== 2) {
// adjacent orange is rotten
vis[newRow][newCol] = 2;
// incrementing time for that orange by 1
q.push([newRow, newCol, t + 1]);
cnt++;
}
}
}
// return time if all fresh oranges are
// rotten, otherwise return -1
return (cnt === freshCount) ? tm : -1;
}
// Driver program
const arr = [
[2, 1, 0, 2, 1],
[1, 0, 1, 2, 1],
[1, 0, 0, 2, 1]
];
const ans = rotOranges(arr);
if (ans === -1) {
console.log("All oranges cannot rot");
} 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.