Rotting Oranges

mediumGraphsmulti-source BFS counting minutesSolve on LeetCode#994

Part of Practice: BFS Waves

A grid (up to 10×10) holds 0 (empty), 1 (fresh orange), or 2 (rotten orange). Every minute, each fresh orange that is directly up, down, left, or right of a rotten one becomes rotten. Return how many minutes pass until no fresh orange remains — or -1 if some fresh orange can never rot. If there are no fresh oranges to begin with, the answer is 0.

Examples

Input:
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output:
4

Rot spreads outward from the top-left orange one ring per minute; the farthest fresh orange (bottom-right) rots at minute 4.

Input:
grid = [[2,1,1],[0,1,1],[1,0,1]]
Output:
-1

The orange at the bottom-left is fenced off by empty cells, so it never rots.

Input:
grid = [[0,2]]
Output:
0

There are no fresh oranges, so zero minutes elapse.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.