Tomatoes
Time limit1sMemory limit256 MB
Given a grid of ripe, unripe, and empty cells, find how many days until every tomato ripens or report -1 if some never can.
Problem
Tomatoes are stored in a warehouse inside a grid-shaped box, one tomato per cell. Each cell of the grid holds a ripe tomato, an unripe tomato, or no tomato at all.

Each day, every unripe tomato that is directly adjacent (up, down, left, or right) to a ripe tomato becomes ripe. Diagonally adjacent tomatoes are not affected, and a tomato never ripens on its own.
Given the size of the grid and the initial state of every cell, find the minimum number of days needed for all tomatoes to ripen. Note that some cells may contain no tomato.
Input
The first line contains two integers and , the dimensions of the box, where is the number of columns and is the number of rows, with .
Each of the next lines describes one row of the box using integers: for a ripe tomato, for an unripe tomato, and for an empty cell.
At least one tomato is guaranteed to be present in the input.
Output
Print the minimum number of days until every tomato is ripe. If all tomatoes are already ripe at the start, print ; if some tomatoes can never ripen, print .