Minutes Until All Oranges Rot
Problem statement
A crate is an m x n grid. Each cell is 0 (empty), 1 (a fresh orange) or 2 (a rotten orange).
Every minute, each fresh orange that shares a side (up, down, left or right) with a rotten orange becomes rotten. All of a minute's changes happen together, so an orange that rots during a minute starts spreading only in the next minute.
Return the number of minutes until no fresh orange is left. Return 0 if there is no fresh orange at the start, and -1 if some fresh orange can never rot.
Function
minutesUntilAllRot(grid: int[][]) → intExamples
Example 1
grid = [[1,1,1],[0,2,1],[0,0,1]]return = 2Minute 1: the rotten orange in the middle rots the one above it and the one to its right. Minute 2: the top-middle orange rots both top corners, and the right-middle orange rots the bottom-right one. No fresh orange is left after 2 minutes.
Example 2
grid = [[2,1,1,1,1,2]]return = 2Both ends spread at the same time. Minute 1 rots positions 1 and 4; minute 2 rots positions 2 and 3. The answer is 2, not the 4 it would take from one end alone.
Example 3
grid = [[1,0],[0,2]]return = -1The fresh orange at the top-left touches the rotten one only at a corner. Rot does not spread diagonally, so it never rots: return -1.
Constraints
1 <= m, n <= 50, wheremis the number of rows andnthe number of columns; every row hasncells- each
grid[i][j]is0,1or2