KatInterview

Greenhouse Disease Spread Timer

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbreadth-first-searchgridmulti-source-bfs

Last updated

Tests multi-source BFS to find the time until a grid-based propagation process completes or determine impossibility.

You manage a greenhouse represented by an m x n grid. Each cell is one of:

  • 0: bare ground (no plant)
  • 1: healthy plant
  • 2: diseased plant

Each day, disease spreads from every diseased plant to all orthogonally adjacent (up, down, left, right) healthy plants simultaneously. Bare ground blocks transmission.

Write a function that returns the number of days until every healthy plant becomes diseased. If some healthy plants can never be reached by the disease, return -1.

Constraints:

  • 1 ≤ m, n ≤ 200
  • Each cell is 0, 1, or 2
  • Your solution should run in O(m × n) time and use O(m × n) space

Examples

Example 1

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

Output: 4

Example 2

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

Output: -1

Example 3

Input: days_to_full_infection([[2, 2], [2, 2]])

Output: 0

Hints

Hint 1

Start BFS from all diseased plants at once rather than spreading from each individually

Hint 2

Mark cells as diseased when you add them to the queue to avoid revisiting

Hint 3

The answer is the maximum distance any healthy plant is from the nearest initial disease source