Intermediate Level

Implement the rottingOrangesMinutes method that returns the minutes required for all fresh oranges to rot.

The input contains a grid of oranges with rows and cols. A value of 0 means an empty cell, 1 means a fresh orange, and 2 means a rotten orange.

Every minute, a rotten orange makes its adjacent fresh oranges rotten. Adjacent means up, down, left, and right.

Your task is to return the minimum number of minutes required until no fresh orange remains. If some fresh orange can never become rotten, return -1.

Example 1
Input:
grid (int[][]) = [[2,1,1],[1,1,0],[0,1,1]]
rows (int) = 3
cols (int) = 3
Return:
(int) 4
Example 2
Input:
grid (int[][]) = [[0,2]]
rows (int) = 1
cols (int) = 2
Return:
(int) 0
Example 3
Input:
grid (int[][]) = [[2,1,1],[0,1,1],[1,0,1]]
rows (int) = 3
cols (int) = 3
Return:
(int) -1

Use breadth-first search starting from all rotten oranges.

Put all initially rotten oranges into a queue and count the fresh oranges. Then process the queue level by level. Each level represents one minute. Whenever a fresh orange becomes rotten, decrease the fresh count and add that cell to the queue.

After BFS finishes, return the minutes if all fresh oranges were reached; otherwise return -1.

Pseudocode:

function rottingOrangesMinutes(grid, rows, cols):
    queue = empty queue
    fresh = 0
    for each cell in grid:
        if cell == 2:
            push cell position into queue
        else if cell == 1:
            fresh++
    minutes = 0
    directions = up, down, left, right
    while queue is not empty and fresh > 0:
        process all cells currently in queue
        for each rotten cell processed:
            for each adjacent cell:
                if adjacent cell is fresh:
                    mark it rotten
                    fresh--
                    push adjacent cell into queue
        minutes++
    if fresh > 0:
        return -1
    return minutes
Run your code to see the result.