KatInterview

Grid Infection Spread with Time Limit

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsbfsgridsimulation

Last updated

Tests BFS-based grid simulation with simultaneous state updates, barrier cells, and handling extremely large iteration counts efficiently.

You are given a rectangular grid representing a forest. Each cell contains one of three characters:

  • 'R' represents an infected tree
  • 'H' represents a healthy tree
  • '-' represents bare ground (no tree)

Each time step, infection spreads simultaneously: every healthy tree that is directly adjacent (up, down, left, or right) to at least one infected tree becomes infected. Diagonal neighbors do not count. Bare ground never becomes infected and does not transmit infection.

Trees that become infected during a particular time step do not spread infection until the next time step.

Given the initial grid state and a number of time steps, return the grid state after that many time steps have elapsed.

Constraints

  • 1 <= len(grid) <= 200
  • 1 <= len(grid[0]) <= 200
  • All rows have equal length
  • Each cell is 'R', 'H', or '-'
  • 0 <= steps <= 10^9

Examples

Example 1

Input: grid_after_infection(['RH-', 'HHH', '-HH'], 1)

Output: ['RR-', 'RHH', '-HH']

Example 2

Input: grid_after_infection(['RH-', 'HHH', '-HH'], 3)

Output: ['RR-', 'RRR', '-RH']

Example 3

Input: grid_after_infection(['H-R'], 5)

Output: ['H-R']

Hints

Hint 1

A naive loop simulating each time step individually will be too slow when steps is very large. What determines when the grid stops changing?

Hint 2

This is a multi-source breadth-first search problem where distance represents time steps. Each BFS level corresponds to one time step.

Hint 3

Process the BFS queue one complete level at a time to ensure trees infected in step N only spread infection in step N+1, not step N.