Skip to content
BytePatterns

Spreading Rot Minutes

MediumGraphs#bfs#multi-source#grid-traversal~30m

Problem

A crate is a grid of cells: 0 is empty, 1 is a fresh fruit and 2 is a rotten one. Every minute, each rotten fruit spoils the fresh fruit directly above, below, left and right of it. Return the number of minutes until no fresh fruit is left, or -1 when some fruit can never be reached.

Examples

Input:  [[2, 1, 1],
         [1, 1, 0],
         [0, 1, 1]]
Output: 4
Why:    the rot spreads outward one ring per minute
Input:  [[2, 1, 1],
         [0, 1, 1],
         [1, 0, 1]]
Output: -1
Why:    the fruit in the bottom left corner is walled off by empty cells
Input:  [[0, 2]]
Output: 0
Why:    edge case, nothing is fresh so no time passes

Hints

0 / 3

Stuck on the idea rather than the code? Multi-Source BFS covers it.