Problem · Array
Rotting Oranges
Learn this problemProblem statement
You are given a rectangular grid whose cells contain 0 for empty, 1 for a fresh orange, or 2 for a rotten orange.
For this exercise, assume every minute each fresh orange orthogonally adjacent to a rotten orange becomes rotten, and all changes in one minute happen simultaneously.
Return the minimum minutes until no fresh orange remains. Return -1 if that is impossible. Return 0 when no fresh orange exists initially.
Function
orangesRotting(grid: int[][]) → intExamples
Example 1
grid = [[2,1,1],[1,1,0],[0,1,1]]return = 4The final fresh orange is reached by the fourth simultaneous breadth-first layer.
Example 2
grid = [[2,1,1],[0,1,1],[1,0,1]]return = -1The lower-left fresh orange is disconnected from every rotten orange.
Example 3
grid = [[0,2]]return = 0No fresh orange exists.
Constraints
1 <= grid.length <= 500.1 <= grid[row].length <= 500.- Every row has the same length.
- Each cell is
0,1, or2.