1. Seed all rotten
Every initially rotten orange starts the BFS at once.
queue.push([r, c])Typorithm · medium
Step 1 of 8 · intro card
Graphs
Seed a BFS with all rotten oranges, spread level by level counting minutes, and return -1 if any fresh remain.
Rot spreads from many sources simultaneously, which is multi-source BFS.
Seed the queue with every rotten orange and count the fresh ones up front.
Each BFS level rots all current neighbors and adds one minute; if fresh oranges remain, return -1.
Seed BFS with all rotten cells.
One level processed = one minute.
Leftover fresh oranges return -1.
function orangesRotting(grid) {
const rows = grid.length;
const cols = grid[0].length;
const queue = [];
let fresh = 0;
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (grid[r][c] === 2) {
queue.push([r, c]);
} else if (grid[r][c] === 1) {
fresh += 1;
}
}
}
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
let minutes = 0;
while (queue.length > 0 && fresh > 0) {
const size = queue.length;
for (let i = 0; i < size; i += 1) {
const [r, c] = queue.shift();
for (const [dr, dc] of dirs) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && grid[nr][nc] === 1) {
grid[nr][nc] = 2;
fresh -= 1;
queue.push([nr, nc]);
}
}
}
minutes += 1;
}
return fresh === 0 ? minutes : -1;
}Connect each part of the code to the concept before you type.
Every initially rotten orange starts the BFS at once.
queue.push([r, c])Track how many fresh oranges remain to rot.
fresh += 1Each BFS level is one minute of rotting.
const size = queue.lengthA fresh neighbor rots and the fresh count drops.
grid[nr][nc] = 2;
fresh -= 1;Leftover fresh oranges mean some can never rot.
return fresh === 0 ? minutes : -1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.