Rotting Oranges

Graphs, problem 4 of 8

Rotting Oranges

Medium

LC #994

gridbfsmulti-source bfs

Not attempted yet

Each cell of a grid is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, each fresh orange that is up, down, left or right of a rotten one becomes rotten.

Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

Example 1

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1

The orange in the bottom-left corner is cut off.

Example 3

Input: grid = [[0,2]]
Output: 0

No fresh oranges, so no time is needed.

Constraints

  • 1 <= rows, cols <= 200
  • grid[r][c] is 0, 1 or 2

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.