Problem · Array
Rotting Oranges
Learn this problemProblem statement
You are given an m x n grid where 0 is an empty cell, 1 is a fresh orange, and 2 is a rotten orange. Every minute, each fresh orange that is orthogonally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes until no fresh orange remains. Return -1 if this is impossible.
Function
orangesRotting(grid: int[][]) → intExamples
Example 1
grid = [[2,1,1],[1,1,0],[0,1,1]]return = 4A breadth-first spread from the initial rotten orange reaches the last fresh orange after four minutes.
Example 2
grid = [[2,1,1],[0,1,1],[1,0,1]]return = -1The fresh orange in the lower-left corner cannot be reached through orthogonal neighbors.
Example 3
grid = [[0,2]]return = 0No fresh orange is present, so zero minutes are needed.
Constraints
1 <= m, n <= 10grid[i][j]is0,1, or2.- Adjacency is orthogonal: up, down, left, or right.