Problem · Array
Minimum Time to Spread Through a Grid
Learn this problemProblem statement
You are given a rectangular grid whose cells contain 0, 1, or 2. A zero is empty, a one is fresh, and a two is already active.
After each minute, every active cell makes each orthogonally adjacent fresh cell active. Return the minimum number of minutes until no fresh cell remains. Return -1 when this is impossible.
Function
minutesToSpread(grid: int[][]) → intExamples
Example 1
grid = [[2,1,1],[1,1,0],[0,1,1]]return = 4The wave reaches the lower-right fresh cell after four minutes.
Example 2
grid = [[2,1,1],[0,1,1],[1,0,1]]return = -1The isolated fresh cell in the lower-left corner is unreachable.
Example 3
grid = [[0,2]]return = 0There are no fresh cells, so no minute needs to pass.
Constraints
1 <= grid.length, grid[r].length <= 200- Every row has the same length.
grid[r][c]is0,1, or2.