Rotting Oranges

Medium Graphs AI round

grid is a map of m rows and n columns. Each cell holds 0 for an empty cell, 1 for a fresh orange or 2 for a rotten orange.

Every minute, each rotten orange turns the fresh oranges next to it rotten: the ones directly above, below, left and right of it, not those at a corner. An orange that turns rotten in one minute starts spreading only in the next minute.

Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never turn rotten. A grid with no fresh orange at the start needs 0 minutes.

Example 1

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

The rot starts in the top left corner and turns one orange a minute along the top row and down: minute 1, minute 2, minute 3. Minute 4 turns two, one to the right and one below; minutes 5 and 6 carry it left along the bottom row, so the last orange, in the bottom left corner, turns in minute 6.

Example 2

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

Example 3

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

Constraints

  • 1 ≤ m, n ≤ 1000
  • m · n ≤ 10⁵
  • Every row of grid has n cells
  • grid[i][j] is 0, 1 or 2

Watch the explanation

More Graphs

All Graphs problems