Problem of the day
You have been given a grid containing some oranges. Each cell of this grid has one of the three integers values:
Every second, any fresh orange that is adjacent(4-directionally) to a rotten orange becomes rotten.
Your task is to find out the minimum time after which no cell has a fresh orange. If it's impossible to rot all the fresh oranges then print -1.
Note:1. The grid has 0-based indexing.
2. A rotten orange can affect the adjacent oranges 4 directionally i.e. Up, Down, Left, Right.
The first line of input contains two single space-separated integers 'N' and 'M' representing the number of rows and columns of the grid respectively.
The next 'N' lines contain 'M' single space-separated integers each representing the rows of the grid.
Output Format:
The only line of output contains a single integer i.e. The minimum time after which no cell has a fresh orange.
If it's impossible to rot all oranges, print -1.
Note:
You are not required to print the expected output, it has already been taken care of. Just implement the function.
1 <= N <= 500
1 <= M <= 500
0 <= grid[i][j] <= 2
Time Limit: 1 sec
3 3
2 1 1
1 1 0
0 1 1
4
Minimum 4 seconds are required to rot all the oranges in the grid as shown below.
3 3
2 1 0
0 1 1
1 0 1
-1
The bottom left corner fresh orange (row 2, column 0) has no adjacent oranges. Hence, it's impossible to rot it.
Try the brute force approach. Every second, rot all fresh oranges adjacent to the rotten oranges.
The idea is very simple and naive. We will process the rotten oranges second by second. Each second, we rot all the fresh oranges that are adjacent to the already rotten oranges. The time by which there are no rotten oranges left to process will be our minimum time.
In the first traversal of the grid, we will process all the cells with value 2 (rotten oranges). We will also mark their adjacent cells as rotten for the next traversal. Now, we can’t mark them by assigning the same value i.e. 2 because then we won’t able to differentiate between the current processing cells and the cells which are going to be processed in the next traversal. So, we will mark them as value 3. More formally, we will be marking the adjacent cells as ‘CURR_ROTTEN’ + 1 in each traversal of the grid.
Here is the complete algorithm.
O(N * M * max(N, M)), where N and M are the numbers of rows and columns of the grid respectively.
In the worst-case scenario, we might end up traversing the whole grid max(N, M) times. This will happen when all the cells have value 1 except a corner cell having value 2.
O(1).
Constant space is used.