Practice · Graphs · 3 of 3

Spreading Rot

You are given grid, where each cell is one of:

  • 0: empty,
  • 1: a fresh orange,
  • 2: a 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. If some fresh orange can never rot, return -1. If there are no fresh oranges to begin with, the answer is 0.

Example 1

Input
grid = [[1, 1, 0, 2], [0, 1, 1, 1], [2, 0, 0, 1]]
Output
5
The rot spreads from the top-right orange down and then left along the middle row; the top-left orange is the last to go, at minute 5. The rotten orange at the bottom left has no fresh neighbour to spread to.

Example 2

Input
grid = [[2, 1], [0, 0], [1, 1]]
Output
-1
The bottom row is cut off by empty cells, so it never rots.

Example 3

Input
grid = [[0, 2], [2, 0]]
Output
0
There are no fresh oranges, so no time is needed.

Constraints

  • The grid has 1 to 100 rows and 1 to 100 columns.
  • Every cell is 0, 1 or 2.