Loading content...
You are given an m × n grid representing a population region where each cell can be in one of three states:
0 represents an empty cell (no population present)1 represents a healthy individual2 represents an infected individualThe infection spreads according to a simple epidemic model: every minute, any healthy individual that is directly adjacent (up, down, left, or right—not diagonal) to an infected individual becomes infected.
Your task is to determine the minimum number of minutes required for the infection to spread to all healthy individuals in the grid. If it is impossible for all healthy individuals to become infected (due to isolation by empty cells or other barriers), return -1.
Key Observations:
grid = [[2,1,1],[1,1,0],[0,1,1]]4The infection originates from the top-left cell (0,0). At minute 1, cells (0,1) and (1,0) become infected. At minute 2, cells (0,2) and (1,1) become infected. At minute 3, cell (2,1) becomes infected. At minute 4, cell (2,2) becomes infected. Total time: 4 minutes.
grid = [[2,1,1],[0,1,1],[1,0,1]]-1The healthy individual in the bottom-left cell (2,0) is completely isolated from all infected cells by empty cells. Infection can only spread horizontally or vertically through adjacent healthy cells, so this individual can never be reached. Therefore, complete infection is impossible.
grid = [[0,2]]0There are no healthy individuals in the grid at the start. The only non-empty cell is already infected. Therefore, zero time is needed for the infection to spread to all healthy individuals (since there are none).
Constraints