Rotting Oranges

Try to solve the Rotting Oranges problem.

Statement#

Consider an m×nm \times n grid containing cells with three potential values:

  • 00, which indicates an unoccupied cell.

  • 11, representing a freshly picked orange.

  • 22, 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 1-1.

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 11 \leq m, n \leq 1010

  • grid[i][j] is 01, or 2.

Examples#

canvasAnimation-image

1 of 11

canvasAnimation-image

2 of 11

canvasAnimation-image

3 of 11

canvasAnimation-image

4 of 11

canvasAnimation-image

5 of 11

canvasAnimation-image

6 of 11

canvasAnimation-image

7 of 11

canvasAnimation-image

8 of 11

canvasAnimation-image

9 of 11

canvasAnimation-image

10 of 11

canvasAnimation-image

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

1

What is the output if the following (3×3)(3 \times 3) grid is given as input?

[211001111]\begin{bmatrix} 2 & 1 & 1 \\ 0 & 0 & 1 \\ 1 & 1 & 1 \end{bmatrix}

A)

3

B)

6

C)

4

Question 1 of 30 attempted

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.

Python
usercode > main.py
Input #1
Rotting Oranges

You might want to go over the Tree Breadth-first Search pattern again.

Solution: Level Order Traversal of Binary Tree

Solution: Rotting Oranges