Under construction

Still being built. Things may change

Tomatoes

Time limit1sMemory limit256 MB

Summary
Given a 3D grid of ripe, unripe, and empty cells, find the minimum days for all tomatoes to ripen via 6-directional spread, or -1 if impossible.
Level

Medium5 of 10

Topics
BFS, Graph, Matrix
Solved
No attempts yet

Problem

Cheolsu's tomato farm has a large warehouse for storing tomatoes. As shown in the figure below, each tomato is placed one per cell of a grid-shaped box, and the boxes are then stacked vertically in the warehouse.

Among the stored tomatoes, some are already ripe while others are not yet ripe. One day after storage, the unripe tomatoes adjacent to a ripe tomato become ripe under its influence. A cell adjacent to a tomato means a tomato in one of the six directions: up, down, left, right, front, and back. Tomatoes in diagonal directions are not affected, and a tomato never ripens on its own.

Given the size of the grid boxes and the information about which tomatoes are ripe and which are not, write a program that determines the minimum number of days until all the stored tomatoes become ripe. Note that some cells of a box may contain no tomato.

Input

The first line contains two integers MM and NN describing the size of a box, and an integer HH describing the number of stacked boxes. Here MM is the number of columns and NN is the number of rows of a box, with 2≤M≤1002 \le M \le 100, 2≤N≤1002 \le N \le 100, and 1≤H≤1001 \le H \le 100.

Starting from the second line, the information of the stored tomatoes is given from the bottom box up to the top box. That is, each box is described by NN lines, and each line contains MM integers describing the state of the tomatoes in that row. The integer 11 denotes a ripe tomato, 00 denotes an unripe tomato, and −1-1 denotes an empty cell with no tomato. Such a block of NN lines is repeated HH times, from the bottom box to the top box.

The input always contains at least one tomato.

Output

Print the minimum number of days until all the tomatoes are ripe. If all the tomatoes are already ripe at the time of storage, print 00; if the tomatoes can never all ripen, print −1-1.

Examples3

  1. Example 1

    Input
    5 3 1
    0 -1 0 0 0
    -1 -1 0 1 1
    0 0 0 1 1
    
    Expected output
    -1
    
  2. Example 2

    Input
    5 3 2
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 0 0 0
    0 0 1 0 0
    0 0 0 0 0
    
    Expected output
    4
    
  3. Example 3

    Input
    4 3 2
    1 1 1 1
    1 1 1 1
    1 1 1 1
    1 1 1 1
    -1 -1 -1 -1
    1 1 1 -1
    
    Expected output
    0