KatInterview

Grid Contagion Simulation

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphsbreadth-first-searchmatrixgraph-traversal

Last updated

Simulate multi-source BFS propagation across a 2D grid up to a maximum number of steps.

You are given a 2D matrix representing a grid of cells. Each cell contains one of three integers:

  • 0: an empty space,
  • 1: an uninfected cell,
  • 2: an infected cell.

Infection spreads synchronously in rounds. During each round, any uninfected cell (1) that shares an edge (up, down, left, or right) with a cell that was already infected (2) at the start of that round becomes infected.

Given the initial grid state and an integer days representing the total number of rounds, return the state of the grid after exactly days rounds have elapsed.

Note:

  • Empty spaces (0) cannot be infected and block the spread of infection.
  • Cells infected during a round cannot spread the infection until the next round.
  • Once infected, a cell remains infected permanently.
  • If days == 0, the grid remains in its initial state.
  • The function should return a new grid and avoid mutating the original input matrix.

Constraints

  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 300
  • grid[r][c] is 0, 1, or 2.
  • 0 <= days <= 10^9

Examples

Example 1

Input: grid_after_days([[2, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 2]], 1)

Output: [[2, 2, 1, 1], [2, 1, 0, 2], [0, 1, 2, 2]]

Example 2

Input: grid_after_days([[2, 1, 1, 1], [1, 1, 0, 1], [0, 1, 1, 2]], 3)

Output: [[2, 2, 2, 2], [2, 2, 0, 2], [0, 2, 2, 2]]

Example 3

Input: grid_after_days([[2, 0, 1], [0, 1, 1]], 5)

Output: [[2, 0, 1], [0, 1, 1]]

Hints

Hint 1

Think of the propagation as a multi-source Breadth-First Search (BFS) where all initial infected cells start at distance 0.

Hint 2

Instead of simulating day-by-day up to 10^9 times, notice that the grid can only change at most O(m * n) times before stopping.

Hint 3

Process the BFS level by level, decrementing or counting steps, and stop early if no new cells become infected.