~/problems / Graphs / BFS / multi-source BFS

Infection spread (multi-part simulation)

hard 4 levels ~75 min OpenAI

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 0 if there is no healthy cell to begin with (this includes an empty grid, [] or [[]]).
  • Return -1 if 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.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc