You are given an m x n grid where each cell is either infected (1) or healthy (0).
Every minute, each infected cell spreads the virus to all of its 4-directionally adjacent healthy cells, turning them infected.
Return the minimum number of minutes until no healthy cell remains. If it is impossible for all cells to become infected, return -1. If there are no healthy cells initially, return 0.
Function Signature
def min_minutes_to_infect(grid: list[list[int]]) -> int:
Rules
-
grid[r][c] == 1
marks an infected cell and
grid[r][c] == 0
marks a healthy cell. Positions below are written
(row, column)
, with
(0, 0)
at the top-left.
-
Adjacent means up, down, left or right. Diagonal cells are not adjacent.
-
All spreading within one minute happens at the same time. A cell infected during a minute starts spreading only in the following minute.
Constraints
-
m == grid.length
-
n == grid[i].length
-
1 <= m, n <= 300
-
grid[i][j]
is
0
or
1
Examples
Input: grid = [[0,1,1],[1,0,0],[0,0,1]]
Output: 1
The cells infected at the start are (0,1), (0,2), (1,0) and (2,2). Every healthy cell already has one of them as a neighbor, so (0,0), (1,1), (1,2), (2,0) and (2,1) all become infected during minute 1.
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,1]]
Output: 2
The virus spreads from the corners (0,0) and (2,3). Minute 1 infects (0,1), (1,0), (1,3) and (2,2), and minute 2 infects the remaining six cells (0,2), (0,3), (1,1), (1,2), (2,0) and (2,1).
Input: grid = [[0,0],[0,0]]
Output: -1
No cell is infected at the start, so the virus has no source and the healthy cells stay healthy forever.