Aphids in the Greenhouse

Mediumbreadth-first searchAlso known as Rotting Oranges

A greenhouse keeps seedlings on a grid. Each spot is empty (0), a healthy plant (1) or a plant with aphids (2). Aphids crawl: each day, every healthy plant directly above, below, left or right of an infested plant becomes infested. Empty spots stop them.

If nobody acts, how many days until every plant is infested? Or are some plants cut off and safe forever?

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

On day 1 the aphids reach (0,1) and (1,0). On day 2 they reach (0,2) and (1,1), on day 3 they reach (2,1), and on day 4 they reach (2,2). Every plant is infested after 4 days.

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

The two infested plants 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 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 and the answer is -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 nothing changes. Then check for healthy plants left.

Each day rescans the grid, and a long winding row of plants can take about one day per plant: up to about 200 days × 400 spots on a 20 × 20 grid. Breadth-first search reaches each plant once.

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