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
Cells are (row, column). The rot follows the only path from (0,0) and reaches (2,3) at minute 5. The orange at (1,3) touches only (2,3), so it rots last, at minute 6.
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 #1

Test #2

Test #3

Argument

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

Expected Output

6