AlgoFrames

Rotting oranges

Standard · Write code · about 20 min

Each cell of grid is 0 (empty), 1 (fresh orange) or 2 (rotten orange). Every minute, each fresh orange next to a rotten one (up, down, left or right) 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:

[[[2,1,1],[1,1,0],[0,1,1]]]

Output:

4

The rot needs 4 minutes to reach the bottom-right orange.

Example 2

Input:

[[[2,1,1],[0,1,1],[1,0,1]]]

Output:

-1

The orange at the bottom-left has no neighbor that can rot it.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • grid[r][c] is 0, 1 or 2

Learn the idea first: 0-1 BFS and multi-source BFS, a visual lesson.

More 0-1 BFS and multi-source BFS problems