KatInterview

Minimum Spread Time for Contamination in a Grid

Trees & GraphsModel answer
MediumModel answerTrees & GraphsBFSmulti-source BFSgrid traversal

Last updated

Find how many steps a contamination spreads from multiple sources through a grid, or determine if some cells remain permanently unaffected.

Contamination Spread in a Grid

You are given an m × n grid of cells. Each cell holds one of three values:

  • 0 — a blocked cell that contamination cannot enter or pass through
  • 1 — a clean cell that can become contaminated
  • 2 — an already-contaminated cell

Every time step, contamination spreads from every contaminated cell to each of its four direct neighbors (up, down, left, right) that is currently clean. All contaminated cells spread simultaneously.

Return the minimum number of time steps required until no clean cell remains anywhere in the grid. If there is at least one clean cell that can never be reached, return -1.

Examples

Input:
2 1 1
1 1 0
0 1 1

Output: 4
Input:
2 1 1
0 1 1
1 0 1

Output: -1   (bottom-left clean cell is walled off)
Input:
0 2 0

Output: 0   (no clean cells to begin with... wait, there are none)
Input:
1 1

Output: -1   (no contaminated source exists)

What is expected

  • Describe your algorithm and explain intuitively why it produces the correct answer.
  • Analyze time and space complexity.
  • Handle all edge cases explicitly.
  • Implement the function in the language of your choice.

Function signature (Python)

def min_steps_to_contaminate(grid: List[List[int]]) -> int:

Constraints

  • 1 ≤ m, n ≤ 10
  • Each cell value is 0, 1, or 2
  • You may not assume there is always at least one contaminated source

Hints

Hint 1

Think about what it means for a clean cell to be contaminated at step k — it must be exactly k hops away from the nearest initially-contaminated cell, with no blocked cells along the path. What algorithm finds shortest distances from multiple sources in one pass?

Hint 2

Instead of running BFS separately from each contaminated source and taking minimums, consider seeding a single BFS queue with all contaminated cells at once at distance 0. This 'virtual super-source' trick finds the nearest-source distance for every reachable cell in O(m·n).

Hint 3

After BFS completes, you need two things to form the answer: the maximum distance seen across all clean cells (that's the step count), and a way to detect whether any clean cell was never reached at all (return -1 in that case). A running counter of remaining clean cells handles both cleanly.