Journal Archive

/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function(grid) {
    const rows = grid.length;
    const cols = grid[0].length;
    let minutes = 0;
    let freshOrange = 0;
    const q = [];
    
    // transverse the grid, noting all fresh & rotten oranges
    for (let i = 0; i < rows; i ++) {
        for (let j = 0; j < cols; j++) {
            if (grid[i][j] === 1) {
                freshOrange += 1;
            }
            else if (grid[i][j] === 2) {
                q.push([i,j])
            }
        }
    }
    // begin BFS
    while (q.length !== 0 && freshOrange > 0) {
        let cellInQ = q.length;
        // deque each rotten and turn neighbour to rotten
        for (let cell = 0; cell < cellInQ; cell++ ) {
            let [row, col] = q.shift();
            
            let neighbours = [
                            [row, col + 1],
                            [row, col - 1],
                            [row + 1, col],
                            [row - 1, col]
                         ];
            
            for (let n of neighbours) {
                // if cell is outside of the matrix or is not fresh
                if (n[0] < 0 || n[0] >= rows || 
                    n[1] >= cols || n[1] < 0 ||
                grid[n[0]][n[1]] !== 1) continue;
                grid[n[0]][n[1]] = 2;
                // add new rotten oranges to queue
                q.push([n[0], n[1]]);
                freshOrange -= 1;
            }
        }
        // increase time after all rotten has infected the fresh
        minutes += 1;
    }
    
    // if still some fresh left then return impossible
    return freshOrange === 0 ? minutes : -1;
};

Day 20: Solving one of LeetCode problems

994. Rotting Oranges Difficulty - Medium

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
        

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
        

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.