Problem 171
Rotting Oranges
Medium · 20 pts · Matrix, Breadth-First Search
Problem
A grid contains empty cells '0', fresh oranges '1' and rotten oranges '2'. Every minute, each fresh orange that is next to a rotten orange (horizontally or vertically) becomes rotten. Print the minimum number of minutes until no fresh orange remains. If some fresh orange can never rot, print -1. If there are no fresh oranges at the start, the answer is 0. Use a multi-source BFS: put all rotten oranges in the queue at time 0 and spread level by level. The time of the last level is the answer.
Input
First line: integers R and C. Next R lines: C characters, each '0', '1' or '2'.
Output
Print the number of minutes, or -1.
Constraints
1 <= R, C <= 300
Example input
3 3 211 110 011
Example output
4
Explanation
The rot starts in the top-left corner. After minute 1 it reaches the two oranges next to it, after minute 2 the next two, after minute 3 the orange in the bottom row, and after minute 4 the last orange in the bottom-right corner. So it takes 4 minutes.