58. Rotting Oranges

In grid, 0 is empty, 1 is a fresh orange and 2 is a rotten orange. Every minute, fresh oranges next to a rotten one (up/down/left/right) become rotten. Return the minutes until no fresh orange is left, or -1 if that never happens.

Example 1

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

Example 2

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

Start a BFS from ALL rotten oranges at the same time (multi-source BFS).

Hint 2

Each BFS layer is one minute.

GraphBFSMatrix