Rotten Oranges

Practice this coding question on Coding Gurukul.

Problem statement

A storage grid contains empty cells, fresh oranges, and rotten oranges. Every minute, all currently rotten oranges spoil fresh oranges sharing an edge with them. The supervisor wants to know when no fresh orange will remain. Your task Return the minimum number of minutes needed to rot every fresh orange, or -1 if some fresh orange can never be reached. Cell values 0, 1 and 2 mean empty, fresh and rotten. Important details Spread happens simultaneously from all rotten cells. Newly rotten oranges begin spreading in the next minute. Empty cells do not transmit rot. If there are initially no fresh oranges, the answer is zero. Worked example For one row [2, 1, 1], the middle orange rots after one minute and the last after two. The answer is 2.

Input format

First line: rows columns. Next rows lines: integer cell values.

Output format

Print the elapsed minutes or -1.

Constraints

1 <= rows, columns <= 10; cells are 0, 1 or 2.

Sample input

1 3
2 1 1

Sample output

2

Sign in to run or submit a solution in C++, Java or Python.