Menu
CoddyTech

Rotting Oranges

MediumGraphsQueuepython iconjava iconcpp iconc iconjs icon+10

You get a grid as a list of rows of equal length. Each cell is 0 (empty), 1 (a fresh orange) or 2 (a rotten orange). Every minute, each fresh orange that shares a side with a rotten orange, up, down, left or right, turns rotten. Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never rot. A grid with no fresh oranges at the start needs 0 minutes.

Function

orangesRotting(grid: integer-2d-array) → integer
gridinteger-2d-array
the grid, one list of 0, 1 and 2 per row
Returnsinteger
the minutes until no orange is fresh, or -1 if that never happens

Constraints

  • 1 ≤ grid.length ≤ 150
  • 1 ≤ grid[i].length ≤ 150
  • Every row has the same length.
  • Each grid[i][j] is 0, 1 or 2.

Examples

Input
grid = [[2, 1, 1, 0], [0, 1, 0, 1], [1, 1, 1, 1]]
Output
6
Explanation
Writing cells as (row, column), the rot leaves (0,0) and follows the only path: (0,1) at minute 1, (0,2) and (1,1) at minute 2, (2,1) at minute 3, (2,0) and (2,2) at minute 4, (2,3) at minute 5. The orange at (1,3) only touches (2,3), so it is the last to go, at minute 6.

lock icon+21 hidden tests on Submit

challenge icon

Follow-up

Suppose each fresh orange needs its own number of minutes to rot once a neighbour is rotten. How would you find the finishing time then?

Reset code
def orangesRotting(grid):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

grid = [[2, 1, 1, 0], [0, 1, 0, 1], [1, 1, 1, 1]]

Expected

6