You are given an m x n grid where each cell can have one of three values: - 0 representing an empty cell, - 1 representing a fresh orange, or - 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Explanation: The rot spreads from the top-left corner one step per minute: (0,1) and (1,0) at minute 1, (0,2) and (1,1) at minute 2, (2,1) at minute 3, and (2,2) at minute 4. After 4 minutes no fresh orange is left.
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange at the bottom-left (2,0) has only empty cells or the edge next to it, so the rot can never reach it. The answer is -1.
Example 3
Input: grid = [[0,2]]
Output: 0
Explanation: There are no fresh oranges at the start, so 0 minutes are needed.
Start BFS from all initially rotten oranges simultaneously. Each BFS level represents one minute of spreading.
Run checks all cases above. Submit evaluates all test cases.