LogiQuest

290. Rotting Oranges

MediumMulti-source BFS

Each minute, fresh oranges (1) adjacent (up/down/left/right) to rotten ones (2) become rotten. Empty cells are 0. Print the minutes until no fresh orange remains, or -1 if impossible.

Input format

Line 1: r c Next r lines: c values

Output format

The minutes, or -1.

Example 1

Input

3 3
2 1 1
1 1 0
0 1 1

Output

4

Example 2

Input

3 3
2 1 1
0 1 1
1 0 1

Output

-1

Constraints

1 ≤ r, c ≤ 500

Read input from standard input and print the answer to standard output. Your code is judged against 4 test cases, most of them hidden.

Loading the MyLoginn IDE…