The Wayback Machine - https://web.archive.org/web/20241001234644/https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/
Open In App

Rotten Oranges – Minimum Time to Rot All

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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));

Output
Max 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.

Using Breadth First Search:

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.

INITIAL-CONFIG

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.

1

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.

2

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.

3

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);
}

Output
Time 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.



Previous Article
Next Article

Similar Reads

Minimum time required to rot all oranges | Dynamic Programming
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 So the task is to 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 or
15 min read
Total Oranges Collection between Given Tree Positions
Given n trees arranged in linear order. The position of trees and oranges contained by a tree is represented by 2D integer array trees[] where 'trees[i] = {x, y}' represents that a tree exists on position 'x' and it contains 'y' oranges on it. There are also q queries[] where queries[i] = {left, right}. For each query, we need to find out the total
10 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Minimum time slots to convert time T1 to T2
Given two strings T1 and T2 representing two time instances in 24-hour formats, the task is to convert T1 to T2 using a minimum number of time slots among 1, 5, 15, or 60 minutes. 24-hour times are formatted as "HH: MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. Examples
7 min read
Minimum time to reach a point with +t and -t moves at time t
Given a positive coordinate 'X' and you are at coordinate '0', the task is to find the minimum time required to get to coordinate 'X' with the following move : At time 't', you can either stay at the same position or take a jump of length exactly 't' either to the left or to the right. In other words, you can be at coordinate 'x - t', 'x' or 'x + t
9 min read
Changing One Clock Time to Other Time in Minimum Number of Operations
Given two clock times (in HH:MM:SS format), change one time to other time in minimum number of operations. Here one operation is meant by shifting the hour, minute or second clock hand by 1 unit in either directions. The program follows all the basic rules of a clock for eg.: changing second's hand from 59 to 0 will make 1 unit change for minute ha
15 min read
Minimum time required to complete all tasks with alteration of their order allowed
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "AAABBB", K
8 min read
Minimum time required to transport all the boxes from source to the destination under the given constraints
Given two arrays, box[] and truck[], where box[i] represents the weight of the ith box and truck[i] represents the maximum load that the ith truck can carry. Now each truck takes 1 hour to transport a box from source to destination and another one hour to come back. Now, given that all the boxes are kept at the source, the task is to find the minim
10 min read
Minimum time to pick all elements with a cooldown period
Given an array arr[] of size n, where each element in the array represents a value between 1 and n. Additionally, you are given another array time[], where time[i] (1 ≤ i ≤ n) represents the minimum time required before you can pick the ith element again after you have already picked it, the task is to determine the minimum amount of time required
7 min read
Minimum time required to visit all the special nodes of a Tree
Given an undirected tree consisting of N vertices where some of the nodes are special nodes, the task is to visit all the special nodes from the root node in minimum time. Time for traveling from one node to another node can be assumed as unit time. A node is special if the path from the root to the node consists of distinct value nodes. Example: I
14 min read
Minimum time required to color all edges of a Tree
Given an array of pairs Edges[][], representing edges connecting vertices in a Tree consisting of N nodes, the task is to find the minimum time required to color all the edges of a Tree based on the assumption that coloring an edge requires 1 unit of time. Note: Multiple edges can be colored on a particular instant, but a node can be part of only o
7 min read
Minimum time to fulfil all orders
Geek is organizing a party at his house. For the party, he needs exactly N (N ? 103) donuts for the guests. Geek decides to order the donuts from a nearby restaurant, which has L chefs and each chef has a rank R. A chef with rank R can make 1 donut in the first R minutes, 1 more donut in next 2R minutes, 1 more donut in 3R minutes, and so on. The t
9 min read
Minimum time required by n cars to travel through all of the m roads
Given m roads and n cars. The cars are numbered from 1 to n. You are also given an array arr[] of size m, each road has a value arr[i] - the index of a car that runs fast on this road. If a car is fast on a road, then it travels across the road in 1 hour, else it takes 2 hours (if not proficient) to travel through this road. Find out the minimum ti
13 min read
Minimum time required to infect all the nodes of Binary tree
Given a binary tree and a node start that is initially infected. For every second, neighbours of an infected node get infected. The task is to find the minimum time in which the whole tree will be infected. Examples: Input: 10 / \ 12 13 / \ 14 15 / \ / \21 22 23 24Start = 14Output: 3 Input: 3 / \ 4 1 \ 2Start = 1Output: 2 An approach using BFS (Bre
15+ min read
Minimum time to reduce all the elements to zero
Given an array of positive integers arr[] of size N. Every second, all the positive values of the array decrease by 1 until they reach zero. Apart from this, we can also perform a special operation in one second to reduce any element by K. If reducing an element by K, makes it negative simply reduce it to zero. Find the minimum time to make all the
7 min read
Minimum time required to complete all tasks without altering their order
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in the given order such that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "ABACCA
6 min read
Find minimum time to finish all jobs with given constraints
Given an array of jobs with different time requirements. There are K identical assignees available and we are also given how much time an assignee takes to do one unit of the job. Find the minimum time to finish all jobs with following constraints. An assignee can be assigned only contiguous jobs. For example, an assignee cannot be assigned jobs 1
12 min read
Minimum time to visit all nodes of given Graph at least once
Given a graph and the list of neighbours for each node in an array graph[] of size N, where graph[i] contains a list of neighbor nodes that are connected to ith node, the task is to visit all the nodes of the given graph in a minimum amount of time. Note: Movement from any node to its neighbour takes one unit of time Example: Input: [[1, 2, 3], [2,
12 min read
Maximum removal from array when removal time >= waiting time
Given there are N elements in an array. The task is to remove elements from the array from left to right. However, some time is required to remove an element from the array(let us call it removal time). The time to remove an element is equal to the value of that element in seconds.An element can only be removed when the time required to remove it(r
6 min read
Maximize time by replacing '_' in a given 24 Hour format time
Given a string S representing a time in 24 hours format, with '_' placed at positions of some digits, the task is to find the maximum time possible by replacing the characters '_' with any digit. Examples: Input: S = “0_:4_”Output: 09:39Explanation: Replacing the characters S[1] and S[4] with '9' modifies the string to "09:49", which is the maximum
7 min read
Total time to pick elements with given time interval
Given an array arr[] of size N that denotes the type of an element, and another time array time[] of size N where time[i] denotes the time interval between picking two elements of the ith type. The task is to find the time taken to pick all the elements while traversing from left to right of the array. Note: Moving between adjacent positions takes
6 min read
Find the positions of given people after T time using their starting time and direction
There's a circular track of length N and given two arrays start[] and direct[] of size M and an integer T, where start[I] represents the starting point of the ith person and direct[I] represents the direction, clockwise if direct[I] is 1, anti-clockwise if direct[I] is -1, the task is to find the positions of all people after T units of time. Note:
7 min read
Find the time which is palindromic and comes after the given time
Given a string str which stores the time in the 24 hours format as HH:MM such that 0 ? HH ? 23 and 0 ? MM ? 59. The task is to find the next closest time which is a palindrome when read as a string. If no such string exists then print -1.Examples: Input: str = "21:12" Output: 22:22 The only palindromic time possible in the given hour is 21:12 but i
10 min read
Minimum product of maximum and minimum element over all possible subarrays
Given an array arr[] consisting of N positive integers, the task is to find the minimum product of maximum and minimum among all possible subarrays. Examples: Input: arr[] = {6, 4, 5, 6, 2, 4}Output: 8Explanation:Consider the subarray {2, 4}, the product of minimum and maximum for this subarray is 2*4 = 8, which is minimum among all possible subarr
4 min read
Minimize sum of minimum and second minimum elements from all possible triplets
Given an array arr[], the task is to minimize the sum of minimum and second minimum elements from all possible triplets. One element can be a part of exactly one triplet. Input: arr[] = {1, 2, 4, 6, 7, 8, 3}, N = 7Output: 10Explanation: Here two triplets are formed as the size of arr[] is 7 and 7/3 = 2.Triplet 1 - {1, 6, 3} -> Two minimum elemen
5 min read
Minimum elements to change so that for an index i all elements on the left are -ve and all elements on the right are +ve
Given an array arr of size n, the task is to find the minimum number of elements that should be changed (element value can be changed to anything) so that there exists an index 0 ? i ? n-2 such that: All the numbers in range 0 to i (inclusive) are < 0.All numbers in range i+1 to n-1 (inclusive) are > 0. Examples: Input: arr[] = {-1, -2, -3, 3
6 min read
Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Minimum operations required to convert a binary string to all 0s or all 1s
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the same length and vice versa. Examples: Input: str =
4 min read
Minimum Time Taken for N Points to coincide
Given an array arr[][] of size N, consisting of pairs of coordinates such that arr[i][0] and arr[i][1] represents the X and Y coordinates in a 2D plane. Given another array V[] that denotes the maximum velocity of each point in any direction, the task is to find the minimum time such that all the given points meet at any arbitrary points in the 2D
15+ min read
Minimum count of subintervals to cover a given time duration
Given an array of intervals[], the task is to find the minimum count of subintervals needed to cover a given time duration. Each interval represents a segment of time that starts at a specific point in time (start time) and ends at another specific point in time (end time). The intervals may overlap and have varying lengths. If it's impossible to c
8 min read