Aphids in the Greenhouse

Mediumbreadth-first searchAlso known as Rotting Oranges

A greenhouse keeps its seedlings in trays laid out on a grid. Each spot is empty (0), holds a healthy plant (1) or holds a plant with aphids (2). Aphids crawl, they do not fly: each day, every healthy plant directly above, below, left or right of an infested plant becomes infested too. Empty spots stop them.

The grower wants to know the worst case if nobody acts. How many days until every plant is infested? Or are some plants safe forever, cut off by empty spots?

Your task

Write daysUntilAllInfested(trays). Return the number of days until no healthy plant is left. Return 0 if there are no healthy plants at the start, and -1 if some healthy plant can never be reached.

All infested plants spread at the same time. A plant infested on day d starts spreading on day d + 1.

daysUntilAllInfested(trays: int[][]) → int

Examples

Example 1
Input
trays = [[2, 1, 1], [1, 1, 0], [0, 1, 1]]
Output
4
Why

Day 1: (0,1) and (1,0). Day 2: (0,2) and (1,1). Day 3: (2,1). Day 4: (2,2). Every plant is infested after 4 days.

Example 2
Input
trays = [[2, 1, 0, 1], [1, 1, 0, 2]]
Output
2
Why

There are two infested plants, and they spread at the same time. The left one reaches (0,1) and (1,0) on day 1 and (1,1) on day 2. The right one reaches (0,3) on day 1. The answer is 2, not the 3 or more you would get by handling one source after the other.

Example 3
Input
trays = [[2, 0, 1]]
Output
-1
Why

The empty spot cuts off the plant on the right, so it is never infested: -1.

Constraints

  • 1 ≤ rows, cols ≤ 20
  • trays[r][c] is 0, 1 or 2
Start with brute force

Simulate day by day: copy the grid, infect every healthy plant next to an infested one, and repeat until a day changes nothing. Then check whether any healthy plant is left.

Each day scans the whole grid, and a long winding row of plants can take about one day per plant. On a 20 × 20 grid that is up to about 200 days × 400 spots. Breadth-first search reaches each plant once instead of rescanning the grid every day.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code