Minutes Until Every Fruit Spoils

MediumGraphs≈ 35 min

A crate of fruit is given as a list of equal-length strings, one per row: o is a fresh fruit, x a spoiled one, and . an empty place. Every minute, each fresh fruit that touches a spoiled fruit up, down, left or right spoils too. Fruit never spoils across an empty place, or diagonally.

Return the number of minutes until no fresh fruit is left. If some fresh fruit can never spoil, return -1. If there is no fresh fruit to begin with, the answer is 0.

Examples

text
["xoo",
 "oo.",
 ".oo"]     →  4

["xoo",
 ".oo",
 "o.o"]     →  -1

[".x."]     →  0

["oxo",
 "ooo"]     →  2

In the second example the fruit in the bottom-left corner has no neighbours at all, so it stays fresh for ever.

Constraints

  • Up to 100 rows and 100 columns.
  • Aim for O(n) in the number of cells: each fruit spoils once, and is looked at from each side once.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.