Problem · Matrix
Rotten Oranges / Grid Infection BFS
Learn this problemProblem statement
You are given a two-dimensional grid representing cells in an infection simulation. Each cell has one of three values:
0: empty1: fresh2: infected
Each minute, every currently infected cell simultaneously infects its 4-directional fresh neighbors. Fresh cells infected during the current minute can only infect other cells in later minutes.
Return the minimum number of minutes needed until there are no fresh cells left. If some fresh cell can never be infected, return -1. If there are no fresh cells at the start, return 0.
Function
minimumMinutesToInfectAll(grid: int[][]) → intExamples
Example 1
grid = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]return = 4The infection spreads level by level from the initial infected cell. The last fresh cell is infected after 4 minutes.
Example 2
grid = [[2, 1, 1], [0, 1, 1], [1, 0, 1]]return = -1The fresh cell in the lower-left corner is isolated by empty cells, so it can never be infected.
Example 3
grid = [[0, 2]]return = 0There are no fresh cells at the start.
Constraints
gridis a rectangular matrix.- Each cell is
0,1, or2. - Infection spreads only in the four orthogonal directions.