Rotting Oranges
Try to solve the Rotting Oranges problem.
We'll cover the following
Statement#
Consider an
, which indicates an unoccupied cell. , representing a freshly picked orange. , indicating a rotten orange.
Any fresh orange that is 4–directionally adjacent to a rotten orange will also turn rotten with each passing minute.
Your task is to determine the minimum time required for all cells to have rotten oranges. In case, this objective cannot be achieved, return
Constraints:
mgrid.lengthngrid[i].lengthm,ngrid[i][j]is0,1, or2.
Examples#
1 of 11
2 of 11
3 of 11
4 of 11
5 of 11
6 of 11
7 of 11
8 of 11
9 of 11
10 of 11
11 of 11
Understand the problem#
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Rotting Oranges
What is the output if the following grid is given as input?
3
6
4
Try it yourself#
Implement your solution in the following coding playground:
The optimal solution to this problem runs in O(m x n) time and takes O(m x n) space.
You might want to go over the Tree Breadth-first Search pattern again.
Solution: Level Order Traversal of Binary Tree
Solution: Rotting Oranges