KatInterview

Calculate Grid Infection Time

Trees & GraphsAuto-graded · 25 test cases
HardAuto-gradedTrees & Graphsbfsgridmulti-source

Last updated

Tests breadth-first search from multiple sources to model time-based propagation in a grid with obstacles and unreachable regions.

You are given an m x n integer grid where each cell contains one of three values:

  • 0 represents a blocked cell
  • 1 represents a healthy cell
  • 2 represents an infected cell

Each minute, any healthy cell that shares an edge (up, down, left, right) with an infected cell becomes infected.

Determine the minimum number of minutes required until every healthy cell becomes infected. If any healthy cell cannot be infected, return -1.

Constraints:

  • 0 ≤ m, n ≤ 100
  • grid[i][j] is 0, 1, or 2
  • Multiple cells may initially be infected
  • The grid may be empty or contain no healthy cells

Examples

Example 1

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

Output: 4

Example 2

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

Output: -1

Example 3

Input: calculate_infection_time([[0, 2]])

Output: 0

Hints

Hint 1

Think about this as a graph problem where infection spreads outward from all initially infected cells simultaneously.

Hint 2

Use breadth-first search starting from all infected cells at once to track how far the infection spreads each minute.

Hint 3

Count the healthy cells at the beginning. As each one gets infected, decrement the count. If the count never reaches zero, some cells are unreachable.