You are given an m x ngrid 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.
Pseudocode
- bfs to look for fresh oranges starting from rotten oranges, moving in 4 directions
- reassign values of fresh oranges, to distance from rotten oranges
Solution
varorangesRotting=function (grid) {if (!grid ||grid.length===0) {return0; }constrow=grid.length;constcolumn= grid[0].length;constqueue= [];let countFresh =0;let minutes =0;let dirs = [ [1,0], [-1,0], [0,1], [0,-1], ];// put the position of all rotten oranges in queue// count the number of fresh orangesfor (let i =0; i < row; i++) {for (let j =0; j < column; j++) {if (grid[i][j] ===2) {queue.push([i, j]); }if (grid[i][j] ===1) { countFresh++; } } }// if count of fresh oranges is zero, return zeroif (countFresh ===0) {return0; }// bfs starting from initially rotten orangeswhile (queue.length!==0&& countFresh) { minutes++;let size =queue.length; // set the size before hand,for (let i =0; i < size; i++) {// if i is limited by queue.length i.e. i < queue.length, queue.length will be vary dynamicallyconstpoint=queue.shift();for (constdirof dirs) {constx= point[0] + dir[0];consty= point[1] + dir[1];// set when to continue, out of bounds, already rotten or empty cellif ( x <0|| y <0|| x >= row || y >= column || grid[x][y] ===2|| grid[x][y] ===0 ) {continue; }// if code reaches here, orange is fresh, mark is as rotten grid[x][y] =2;// book keeping, if not all fresh oranges are rotten, return -1 countFresh--;// push this the coords of this newly rotten orange into queue to look for next fresh orangequeue.push([x, y]); } } }// count - 1 because minute is 0 based indexreturn countFresh ===0? minutes :-1;};