Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Rotten Orange Grid Traversal Algorithm | 2D Array | Graph Traversal Algo
Mar 18, 2025
350 views
You are given an m x n grid where each cell can have one of three values:
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.
Situation:
Task:
return -1
Action:
var orangesRotting = function(grid) { const directions = [ [-1, 0], [0, 1], [1, 0], [0, -1] ] function inBound(value, max){ return -1 < value && value < max }A Normal BFS:
function bfs(){ let queue = [] queue.push([0, 0]) while(queue.length){ const [row, col] = queue.shift() for(let [dirRow, dirCol] of dir){ let newRow = row + dirRow let newCol = col + dirCol if(inBound(newRow, grid[0].length) && inBound(newCol, grid[1].length)){ queue.push([newRow, newCol]) } } } }function bfsLevel(queue){ let min = 0 let totalRotten = 0 while(0 < queue.length){ let queueSize = queue.length let count = 0 while( count < queueSize){ const [row, col] = queue.shift() for(let [dirRow, dirCol] of directions){ let newRow = row + dirRow let newCol = col + dirCol if(inBound(newRow, grid.length) && inBound(newCol, grid[0].length) && grid[newRow][newCol] === 1){ grid[newRow][newCol] = 2 totalRotten++ queue.push([newRow, newCol]) } } count++ } if(queue.length){ min++ } } return {min, totalRotten} }const queue = [] let fresh = 0 for(let i = 0; i < grid.length; i++){ for(let j = 0; j < grid[0].length; j++){ if(grid[i][j] === 2){ queue.push([i, j]) } if(grid[i][j] === 1){ fresh++ } } } let {min, totalRotten} = bfsLevel(queue) return totalRotten === fresh ? min : -1 };why is this line very important?
if(queue.length){ min++ }The line if (queue.length) min++ is crucial in the bfsLevel function because it ensures that the min counter is only incremented when there are still oranges to process in the next level of the BFS traversal. Here's why it's important:
Explanation of the Code Logic
Why if (queue.length) min++ is Important