The Wayback Machine - https://web.archive.org/web/20250214134050/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 : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
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).

Note : 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] – Using Iteration – O((n * m) ^ 2) Time and O(1) Space

The idea is iteratively change the cells with fresh orange connected to that of rotten orange until either there is no cell with fresh orange or it is not possible to reach the fresh orange

  • 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.
  • At last check if there is any fresh orange remaining, if so print -1, else print the elapsed time.
C++
// C++ Program to find the minimum time
// in which all oranges will get rotten
#include <bits/stdc++.h>
using namespace std;

// Check if i, j is within the array
// limits of row and column
bool isSafe(int i, int j, int n, int m) {
    return (i >= 0 && i < n && j >= 0 && j < m);
}

int orangesRotting(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();

    // to check if any changes are made
    bool changed = false;

    // counter of elapsed time
    int elapsedTime = 0;

    // all four directions
    vector<vector<int>> directions = { { 1, 0 }, { 0, 1 }, 
                            { -1, 0 }, { 0, -1 } };

    // iterate until changes are there
    while (true) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            
            // check if the cell was marked in last iteration
            if (mat[i][j] == elapsedTime + 2) {

                // change 4-directionally connected cells
                for(auto dir: directions) {
                    int x = i + dir[0];
                    int y = j + dir[1];

                    // if cell is in the matrix and
                    // the orange is fresh
                    if(isSafe(x, y, n, m) && mat[x][y] == 1) {
                        mat[x][y] = mat[i][j] + 1;
                        changed = true;
                    }
                }
            }
        }
    }

    // if no changes are done
    if (!changed) break;
    changed = false;
    elapsedTime++;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          
            // if any orange is found
            // not rotten, return -1
            if (mat[i][j] == 1) return -1;
        }
    }

    return elapsedTime;
}

int main() {
    vector<vector<int>> mat = { { 0, 1, 2 },
                              { 0, 1, 2 },
                              { 2, 1, 1 } };
    cout << orangesRotting(mat);
    return 0;
}
Java
// Java Program to find the minimum time
// in which all oranges will get rotten
import java.util.*;

class GfG {
    static boolean isSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    static int orangesRotting(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        // to check if any changes are made
        boolean changed = false;

        // counter of elapsed time
        int elapsedTime = 0;

        // all four directions
        int[][] directions = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

        // iterate until changes are there
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {

                    // check if the cell was marked in last iteration
                    if (mat[i][j] == elapsedTime + 2) {

                        // change 4-directionally connected cells
                        for (int[] dir : directions) {
                            int x = i + dir[0];
                            int y = j + dir[1];

                            // if cell is in the matrix and
                            // the orange is fresh
                            if (isSafe(x, y, n, m) && mat[x][y] == 1) {
                                mat[x][y] = mat[i][j] + 1;
                                changed = true;
                            }
                        }
                    }
                }
            }

            // if no changes are done
            if (!changed) break;
            changed = false;
            elapsedTime++;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if any orange is found
                // not rotten, return -1
                if (mat[i][j] == 1) return -1;
            }
        }

        return elapsedTime;
    }

    public static void main(String[] args) {
        int[][] mat = { { 0, 1, 2 },
                        { 0, 1, 2 },
                        { 2, 1, 1 } };
        System.out.println(orangesRotting(mat));
    }
}
Python
# Python Program to find the minimum time
# in which all oranges will get rotten

def isSafe(i, j, n, m):
    return 0 <= i < n and 0 <= j < m

def orangesRotting(mat):
    n = len(mat)
    m = len(mat[0])

    # to check if any changes are made
    changed = False

    # counter of elapsed time
    elapsedTime = 0

    # all four directions
    directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]

    # iterate until changes are there
    while True:
        for i in range(n):
            for j in range(m):

                # check if the cell was marked in last iteration
                if mat[i][j] == elapsedTime + 2:

                    # change 4-directionally connected cells
                    for dir in directions:
                        x = i + dir[0]
                        y = j + dir[1]

                        # if cell is in the matrix and
                        # the orange is fresh
                        if isSafe(x, y, n, m) and mat[x][y] == 1:
                            mat[x][y] = mat[i][j] + 1
                            changed = True

        # if no changes are done
        if not changed:
            break
        changed = False
        elapsedTime += 1

    for i in range(n):
        for j in range(m):

            # if any orange is found
            # not rotten, return -1
            if mat[i][j] == 1:
                return -1

    return elapsedTime

if __name__ == "__main__":
    mat = [[0, 1, 2],
           [0, 1, 2],
           [2, 1, 1]]
    
    print(orangesRotting(mat))
C#
// C# Program to find the minimum time
// in which all oranges will get rotten
using System;
using System.Collections.Generic;

class GfG {
    static bool IsSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    static int OrangesRotting(int[][] mat) {
        int n = mat.Length;
        int m = mat[0].Length;

        // to check if any changes are made
        bool changed = false;

        // counter of elapsed time
        int elapsedTime = 0;

        // all four directions
        int[][] directions = new int[][] {
            new int[] { 1, 0 }, new int[] { 0, 1 },
            new int[] { -1, 0 }, new int[] { 0, -1 }
        };

        // iterate until changes are there
        while (true) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {

                    // check if the cell was marked in last iteration
                    if (mat[i][j] == elapsedTime + 2) {

                        // change 4-directionally connected cells
                        foreach (var dir in directions) {
                            int x = i + dir[0];
                            int y = j + dir[1];

                            // if cell is in the matrix and
                            // the orange is fresh
                            if (IsSafe(x, y, n, m) && mat[x][y] == 1) {
                                mat[x][y] = mat[i][j] + 1;
                                changed = true;
                            }
                        }
                    }
                }
            }

            // if no changes are done
            if (!changed) break;
            changed = false;
            elapsedTime++;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if any orange is found
                // not rotten, return -1
                if (mat[i][j] == 1) return -1;
            }
        }

        return elapsedTime;
    }

    static void Main(string[] args) {
        int[][] mat = {
            new int[] { 0, 1, 2 },
            new int[] { 0, 1, 2 },
            new int[] { 2, 1, 1 }
        };
        Console.WriteLine(OrangesRotting(mat));
    }
}
JavaScript
// JavaScript Program to find the minimum time
// in which all oranges will get rotten

function isSafe(i, j, n, m) {
    return i >= 0 && i < n && j >= 0 && j < m;
}

function orangesRotting(mat) {
    let n = mat.length;
    let m = mat[0].length;

    // to check if any changes are made
    let changed = false;

    // counter of elapsed time
    let elapsedTime = 0;

    // all four directions
    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];

    // iterate until changes are there
    while (true) {
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < m; j++) {

                // check if the cell was marked in last iteration
                if (mat[i][j] === elapsedTime + 2) {

                    // change 4-directionally connected cells
                    for (const dir of directions) {
                        let x = i + dir[0];
                        let y = j + dir[1];

                        // if cell is in the matrix and
                        // the orange is fresh
                        if (isSafe(x, y, n, m) && mat[x][y] === 1) {
                            mat[x][y] = mat[i][j] + 1;
                            changed = true;
                        }
                    }
                }
            }
        }

        // if no changes are done
        if (!changed) break;
        changed = false;
        elapsedTime++;
    }

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // if any orange is found
            // not rotten, return -1
            if (mat[i][j] === 1) return -1;
        }
    }

    return elapsedTime;
}

// Driver Code
const mat = [
    [0, 1, 2],
    [0, 1, 2],
    [2, 1, 1]
];

console.log(orangesRotting(mat));

Output
1

[Better Approach] – Using Depth First Search – O(n * m) Time and O(1) Space

  • The idea is to perform DFS from each rotten orange and find the minimum time required to rot all the fresh oranges.
  • Traverse through all the cells of matrix mat[][], if cell mat[i][j] == 2, i.e. it has a rotten orange, perform DFS to rot all the connected fresh oranges.
  • In each recursive call, check for all 4-directionally connected cells, if any cell contains a fresh orange or the time required to rot it is less than previously stored value, move to that cell.
  • At last check if there is any fresh orange remaining, if so print -1, else print the maximum elapsed time.
C++
// C++ Program to find the minimum time
// in which all oranges will get rotten
#include <bits/stdc++.h>
using namespace std;

// Check if i, j is within the array
// limits of row and column
bool isSafe(int i, int j, int n, int m) {
    return (i >= 0 && i < n && j >= 0 && j < m);
}

// function to perform dfs and find fresh orange
void dfs(vector<vector<int>>& mat, int i , 
                                int j, int time){
    int n = mat.size();
    int m = mat[0].size();

    // update minimum time
    mat[i][j] = time;

    // all four directions
    vector<vector<int>> directions = 
        { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

    // change 4-directionally connected cells
    for(auto dir: directions) {
        int x = i + dir[0];
        int y = j + dir[1];

        // if cell is in the matrix and
        // the orange is fresh
        if(isSafe(x, y, n, m) && 
           (mat[x][y] == 1 || mat[x][y] > time + 1)) {
            dfs(mat, x, y, time + 1);
        }
    }
}

int orangesRotting(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();

    // counter of elapsed time
    int elapsedTime = 0;

    // iterate through all the cells
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {

            // if orange is initiall rotten
            if (mat[i][j] == 2) {
                dfs(mat, i, j, 2);
            }
        }
    }
    // iterate through all the cells
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {

            // if orange is fresh
            if(mat[i][j] == 1)
                return -1;

            // update the maximum time
            elapsedTime = max(elapsedTime, mat[i][j] - 2);
        }
    }
    return elapsedTime;
}

int main() {
    vector<vector<int>> mat = { { 0, 1, 2 },
                              { 0, 1, 2 },
                              { 2, 1, 1 } };
    cout << orangesRotting(mat);
    return 0;
}
Java
// Java Program to find the minimum time
// in which all oranges will get rotten
import java.util.*;

class GfG {

    // Check if i, j is within the array
    // limits of row and column
    static boolean isSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    // function to perform dfs and find fresh orange
    static void dfs(int[][] mat, int i, int j, int time) {
        int n = mat.length;
        int m = mat[0].length;

        // update minimum time
        mat[i][j] = time;

        // all four directions
        int[][] directions = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

        // change 4-directionally connected cells
        for (int[] dir : directions) {
            int x = i + dir[0];
            int y = j + dir[1];

            // if cell is in the matrix and
            // the orange is fresh
            if (isSafe(x, y, n, m) &&
                (mat[x][y] == 1 || mat[x][y] > time + 1)) {
                dfs(mat, x, y, time + 1);
            }
        }
    }

    static int orangesRotting(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        // counter of elapsed time
        int elapsedTime = 0;

        // iterate through all the cells
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if orange is initially rotten
                if (mat[i][j] == 2) {
                    dfs(mat, i, j, 2);
                }
            }
        }

        // iterate through all the cells
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if orange is fresh
                if (mat[i][j] == 1)
                    return -1;

                // update the maximum time
                elapsedTime = Math.max(elapsedTime, mat[i][j] - 2);
            }
        }
        return elapsedTime;
    }

    public static void main(String[] args) {
        int[][] mat = { { 0, 1, 2 },
                        { 0, 1, 2 },
                        { 2, 1, 1 } };
        System.out.println(orangesRotting(mat));
    }
}
Python
# Python Program to find the minimum time
# in which all oranges will get rotten

def is_safe(i, j, n, m):
    return 0 <= i < n and 0 <= j < m

# function to perform dfs and find fresh orange
def dfs(mat, i, j, time):
    n = len(mat)
    m = len(mat[0])

    # update minimum time
    mat[i][j] = time

    # all four directions
    directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]

    # change 4-directionally connected cells
    for dir in directions:
        x = i + dir[0]
        y = j + dir[1]

        # if cell is in the matrix and
        # the orange is fresh
        if is_safe(x, y, n, m) and (mat[x][y] == 1 or mat[x][y] > time + 1):
            dfs(mat, x, y, time + 1)

def oranges_rotting(mat):
    n = len(mat)
    m = len(mat[0])

    # counter of elapsed time
    elapsed_time = 0

    # iterate through all the cells
    for i in range(n):
        for j in range(m):

            # if orange is initially rotten
            if mat[i][j] == 2:
                dfs(mat, i, j, 2)

    # iterate through all the cells
    for i in range(n):
        for j in range(m):

            # if orange is fresh
            if mat[i][j] == 1:
                return -1

            # update the maximum time
            elapsed_time = max(elapsed_time, mat[i][j] - 2)

    return elapsed_time

if __name__ == "__main__":
    mat = [[0, 1, 2],
           [0, 1, 2],
           [2, 1, 1]]
    
    print(oranges_rotting(mat))
C#
// C# Program to find the minimum time
// in which all oranges will get rotten
using System;

class GfG {

    // Check if i, j is within the array
    // limits of row and column
    static bool IsSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    // function to perform dfs and find fresh orange
    static void Dfs(int[][] mat, int i, int j, int time) {
        int n = mat.Length;
        int m = mat[0].Length;

        // update minimum time
        mat[i][j] = time;

        // all four directions
        int[][] directions = {
            new int[] { 1, 0 }, new int[] { 0, 1 },
            new int[] { -1, 0 }, new int[] { 0, -1 }
        };

        // change 4-directionally connected cells
        foreach (var dir in directions) {
            int x = i + dir[0];
            int y = j + dir[1];

            // if cell is in the matrix and
            // the orange is fresh
            if (IsSafe(x, y, n, m) &&
                (mat[x][y] == 1 || mat[x][y] > time + 1)) {
                Dfs(mat, x, y, time + 1);
            }
        }
    }

    static int OrangesRotting(int[][] mat) {
        int n = mat.Length;
        int m = mat[0].Length;

        // counter of elapsed time
        int elapsedTime = 0;

        // iterate through all the cells
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if orange is initially rotten
                if (mat[i][j] == 2) {
                    Dfs(mat, i, j, 2);
                }
            }
        }

        // iterate through all the cells
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // if orange is fresh
                if (mat[i][j] == 1)
                    return -1;

                // update the maximum time
                elapsedTime = Math.Max(elapsedTime, mat[i][j] - 2);
            }
        }
        return elapsedTime;
    }

    static void Main(string[] args) {
        int[][] mat = {
            new int[] { 0, 1, 2 },
            new int[] { 0, 1, 2 },
            new int[] { 2, 1, 1 }
        };
        Console.WriteLine(OrangesRotting(mat));
    }
}
JavaScript
// JavaScript Program to find the minimum time
// in which all oranges will get rotten

function isSafe(i, j, n, m) {
    return i >= 0 && i < n && j >= 0 && j < m;
}

// function to perform dfs and find fresh orange
function dfs(mat, i, j, time) {
    const n = mat.length;
    const m = mat[0].length;

    // update minimum time
    mat[i][j] = time;

    // all four directions
    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];

    // change 4-directionally connected cells
    for (const dir of directions) {
        const x = i + dir[0];
        const y = j + dir[1];

        // if cell is in the matrix and
        // the orange is fresh
        if (isSafe(x, y, n, m) &&
            (mat[x][y] === 1 || mat[x][y] > time + 1)) {
            dfs(mat, x, y, time + 1);
        }
    }
}

function orangesRotting(mat) {
    const n = mat.length;
    const m = mat[0].length;

    // counter of elapsed time
    let elapsedTime = 0;

    // iterate through all the cells
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // if orange is initially rotten
            if (mat[i][j] === 2) {
                dfs(mat, i, j, 2);
            }
        }
    }

    // iterate through all the cells
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // if orange is fresh
            if (mat[i][j] === 1)
                return -1;

            // update the maximum time
            elapsedTime = Math.max(elapsedTime, mat[i][j] - 2);
        }
    }
    return elapsedTime;
}

// Driver Code
const mat = [
    [0, 1, 2],
    [0, 1, 2],
    [2, 1, 1]
];

console.log(orangesRotting(mat));

Output
1

[Expected Approach] – Using Breadth First Search – O(n * m) Time and O(n * m) Space

The idea is to use Breadth First Search to find the minimum time required.

  • Create a queue to store all the cells that initially contains rotten orange.
  • Now, run a loop until queue is not empty and in each iteration dequeue the top most element, storing the time and indices of cell. Now check all 4-directionally connected cell, if any cell contains a fresh orange, change its state and push the indices in queue and increment the time by 1.
  • After the queue is empty, check if there is any fresh orange remaining, if so print -1, else print the maximum elapsed time.

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

C++
// C++ Program to find the minimum time
// in which all oranges will get rotten

#include <bits/stdc++.h>
using namespace std;

// Check if i, j is within the array
// limits of row and column
bool isSafe(int i, int j, int n, int m) {
    return (i >= 0 && i < n && j >= 0 && j < m);
}

int orangesRotting(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();

    // all four directions
    vector<vector<int>> directions = { { 1, 0 }, { 0, 1 }, 
                            { -1, 0 }, { 0, -1 } };

    // queue to store cell position
    queue<vector<int>> q;

    // find all rotten oranges
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (mat[i][j] == 2) {
                q.push({ i, j });
            }
        }
    }
    
    // counter of elapsed time
    int elapsedTime = 0;

    while (!q.empty()) {

        // increase time by 1
        elapsedTime++;

        int len = q.size();
        while(len--) {
            vector<int> cur = q.front();
            q.pop();
            int i = cur[0];
            int j = cur[1];

            // change 4-directionally connected cells
            for(auto dir: directions) {
                int x = i + dir[0];
                int y = j + dir[1];

                // if cell is in the matrix and
                // the orange is fresh
                if(isSafe(x, y, n, m) && mat[x][y] == 1) {
                    mat[x][y] = 2;
                    q.push({ x, y });
                }
            }
        }
    }

    // check if any fresh orange is remaining
    for(int i = 0; i<n; i++) {
        for(int j = 0; j<m; j++) {
            if(mat[i][j] == 1) {
                return -1;
            }
        }
    }

    return max(0, elapsedTime-1);
}

int main() {
    vector<vector<int>> mat = { { 0, 1, 2 },
                              { 0, 1, 2 },
                              { 2, 1, 1 } };
    cout << orangesRotting(mat);
    return 0;
}
Java
// Java Program to find the minimum time
// in which all oranges will get rotten
import java.util.*;

class GfG {

    // Check if i, j is within the array
    // limits of row and column
    static boolean isSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    static int orangesRotting(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        // all four directions
        int[][] directions = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

        // queue to store cell position
        Queue<int[]> q = new LinkedList<>();

        // find all rotten oranges
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 2) {
                    q.add(new int[] { i, j });
                }
            }
        }

        // counter of elapsed time
        int elapsedTime = 0;

        while (!q.isEmpty()) {

            // increase time by 1
            elapsedTime++;

            int len = q.size();
            while (len-- > 0) {
                int[] cur = q.poll();
                int i = cur[0];
                int j = cur[1];

                // change 4-directionally connected cells
                for (int[] dir : directions) {
                    int x = i + dir[0];
                    int y = j + dir[1];

                    // if cell is in the matrix and
                    // the orange is fresh
                    if (isSafe(x, y, n, m) && mat[x][y] == 1) {
                        mat[x][y] = 2;
                        q.add(new int[] { x, y });
                    }
                }
            }
        }

        // check if any fresh orange is remaining
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 1) {
                    return -1;
                }
            }
        }

        return Math.max(0, elapsedTime - 1);
    }

    public static void main(String[] args) {
        int[][] mat = { { 0, 1, 2 },
                        { 0, 1, 2 },
                        { 2, 1, 1 } };
        System.out.println(orangesRotting(mat));
    }
}
Python
# Python Program to find the minimum time
# in which all oranges will get rotten
from collections import deque

# Check if i, j is within the array
# limits of row and column
def isSafe(i, j, n, m):
    return 0 <= i < n and 0 <= j < m

def orangesRotting(mat):
    n = len(mat)
    m = len(mat[0])

    # all four directions
    directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]

    # queue to store cell position
    q = deque()

    # find all rotten oranges
    for i in range(n):
        for j in range(m):
            if mat[i][j] == 2:
                q.append((i, j))

    # counter of elapsed time
    elapsedTime = 0

    while q:
        # increase time by 1
        elapsedTime += 1

        for _ in range(len(q)):
            i, j = q.popleft()

            # change 4-directionally connected cells
            for dir in directions:
                x = i + dir[0]
                y = j + dir[1]

                # if cell is in the matrix and
                # the orange is fresh
                if isSafe(x, y, n, m) and mat[x][y] == 1:
                    mat[x][y] = 2
                    q.append((x, y))

    # check if any fresh orange is remaining
    for i in range(n):
        for j in range(m):
            if mat[i][j] == 1:
                return -1

    return max(0, elapsedTime - 1)

if __name__ == "__main__":
    mat = [[0, 1, 2],
           [0, 1, 2],
           [2, 1, 1]]
    
    print(orangesRotting(mat))
C#
// C# Program to find the minimum time
// in which all oranges will get rotten
using System;
using System.Collections.Generic;

class GfG {

    // Check if i, j is within the array
    // limits of row and column
    static bool IsSafe(int i, int j, int n, int m) {
        return (i >= 0 && i < n && j >= 0 && j < m);
    }

    static int OrangesRotting(int[][] mat) {
        int n = mat.Length;
        int m = mat[0].Length;

        // all four directions
        int[][] directions = {
            new int[] { 1, 0 }, new int[] { 0, 1 },
            new int[] { -1, 0 }, new int[] { 0, -1 }
        };

        // queue to store cell position
        Queue<int[]> q = new Queue<int[]>();

        // find all rotten oranges
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 2) {
                    q.Enqueue(new int[] { i, j });
                }
            }
        }

        // counter of elapsed time
        int elapsedTime = 0;

        while (q.Count > 0) {

            // increase time by 1
            elapsedTime++;

            int len = q.Count;
            while (len-- > 0) {
                int[] cur = q.Dequeue();
                int i = cur[0];
                int j = cur[1];

                // change 4-directionally connected cells
                foreach (var dir in directions) {
                    int x = i + dir[0];
                    int y = j + dir[1];

                    // if cell is in the matrix and
                    // the orange is fresh
                    if (IsSafe(x, y, n, m) && mat[x][y] == 1) {
                        mat[x][y] = 2;
                        q.Enqueue(new int[] { x, y });
                    }
                }
            }
        }

        // check if any fresh orange is remaining
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 1) {
                    return -1;
                }
            }
        }

        return Math.Max(0, elapsedTime - 1);
    }

    static void Main(string[] args) {
        int[][] mat = {
            new int[] { 0, 1, 2 },
            new int[] { 0, 1, 2 },
            new int[] { 2, 1, 1 }
        };
        Console.WriteLine(OrangesRotting(mat));
    }
}
JavaScript
// JavaScript Program to find the minimum time
// in which all oranges will get rotten

// Check if i, j is within the array
// limits of row and column
function isSafe(i, j, n, m) {
    return i >= 0 && i < n && j >= 0 && j < m;
}

function orangesRotting(mat) {
    const n = mat.length;
    const m = mat[0].length;

    // all four directions
    const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];

    // queue to store cell position
    const q = [];

    // find all rotten oranges
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (mat[i][j] === 2) {
                q.push([i, j]);
            }
        }
    }

    // counter of elapsed time
    let elapsedTime = 0;

    while (q.length > 0) {

        // increase time by 1
        elapsedTime++;

        let len = q.length;
        while (len-- > 0) {
            const [i, j] = q.shift();

            // change 4-directionally connected cells
            for (const dir of directions) {
                const x = i + dir[0];
                const y = j + dir[1];

                // if cell is in the matrix and
                // the orange is fresh
                if (isSafe(x, y, n, m) && mat[x][y] === 1) {
                    mat[x][y] = 2;
                    q.push([x, y]);
                }
            }
        }
    }

    // check if any fresh orange is remaining
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (mat[i][j] === 1) {
                return -1;
            }
        }
    }

    return Math.max(0, elapsedTime - 1);
}

// Driver Code
const mat = [
    [0, 1, 2],
    [0, 1, 2],
    [2, 1, 1]
];

console.log(orangesRotting(mat));

Output
1


Next Article

Similar Reads

three90RightbarBannerImg