Rotting Oranges

In this tutorial, i am going to discuss a very interesting problem rotting oranges (minimum time required to rot all fresh oranges).

Given an m*n grid where each cell in the matrix can have values 0, 1 or 2.

0 represents an empty cell
1 represents cells have fresh oranges
2 represents cells have rotten oranges

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

For example –

In the below example, we have given the grid, it takes 4 minute to rot all fresh oranges.

Rotting oranges explained with example.

This is the problem statement, let’s think how we can solve this problem efficiently.

Programming video tutorials

Rotting Oranges – Java Code & Explanation

In this problem, we have to find the time taken to rot all fresh oranges, if it’s not possible then return -1.

How to approach this problem?

i) To solve this problem, the first step is to find all the oranges that are initially rotten.

ii) In the next one minute, these rotten oranges will rot the neighbouring fresh oranges. And this process will continue till all the rotten oranges have rot their adjacent fresh oranges.

Imagine this process in breadth first manner (level by level). First we track all the rotten oranges (Imagine it is at level 0). Then these rotten oranges rot their adjacent fresh oranges and so on (In level 1, 2 etc). So, the time required to rot all oranges is equal to the number of levels.


We have to handle one more case. Suppose, if there are no fresh oranges in the grid. In that case simply return 0.

Steps to solve this problem


i) Declare a queue to keep all the rotten oranges.

ii) Iterate the grid and add all the rotten oranges in the queue. Also, declare one variable to store the count of fresh oranges.

iii) If there is no fresh oranges in grid then return zero. Else run a loop dequeue the rotten oranges from a queue and rot all the adjacent oranges. In this process decrement the count of fresh oranges and enqueue rotten oranges in a queue. After this process increment the value of count (which keeps track of minute).

Number of islands


Repeat this process until we have no more rotten oranges.


If the number of fresh oranges after the entire process is still not zero, then return -1 indicating that it’s impossible to rot all the oranges.
Else return the time required to rot all the oranges.

The time complexity of this approach is O(m*n) where m and n is the length of row and column.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.