Level 1 Basic spread
A rectangular grid holds 0 (healthy) and 1 (infected). Each day, every infected cell infects its healthy neighbours up, down, left and right (no diagonals). All cells update at the same time: a cell infected today only starts spreading tomorrow.
Implement time_to_full_infection(grid) -> int:
- Return the number of days until no healthy cell is left.
- Return
0if there is no healthy cell to begin with (this includes an empty grid,[]or[[]]). - Return
-1if some healthy cell can never be infected (here that only happens when there is no infected cell at all). - Don't modify
grid.
time_to_full_infection([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]) # 2: edges on day 1, corners on day 2
time_to_full_infection([[0, 0, 0, 1]]) # 3
time_to_full_infection([[0, 0]]) # -1: nothing can start the spread
Grids can be a few hundred cells on a side and the spread can take thousands of days, so re-scanning the whole grid every day is too slow: aim for O(rows·cols) in total.
Show hint
Only the cells infected yesterday can infect anything new today. Keep those in a queue, starting with all of the initially infected cells together, and handle one day's batch at a time.