⬅ Previous Topic
Connected Components in a MatrixNext Topic ⮕
Flood Fill Algorithm - Graph Based⬅ Previous Topic
Connected Components in a MatrixNext Topic ⮕
Flood Fill Algorithm - Graph BasedTopic Contents
You are given an m x n
grid representing a box of oranges. Each cell of the grid can have one of the following values:
0
: an empty cell1
: a fresh orange2
: a rotten orangeEach minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Your task is to return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1
.
function orangesRotting(grid) {
const rows = grid.length, cols = grid[0].length;
const queue = [];
let fresh = 0, time = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 2) queue.push([r, c, 0]);
if (grid[r][c] === 1) fresh++;
}
}
const directions = [[0,1],[1,0],[0,-1],[-1,0]];
while (queue.length > 0) {
const [r, c, t] = queue.shift();
time = Math.max(time, t);
for (const [dr, dc] of directions) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) {
grid[nr][nc] = 2;
fresh--;
queue.push([nr, nc, t + 1]);
}
}
}
return fresh === 0 ? time : -1;
}
console.log("Minutes to rot all oranges:", orangesRotting([[2,1,1],[1,1,0],[0,1,1]])); // 4
console.log("Minutes to rot all oranges:", orangesRotting([[2,1,1],[0,1,1],[1,0,1]])); // -1
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(m * n) | Even in the best case, we must scan the entire matrix to identify the initial rotten and fresh oranges. |
Average Case | O(m * n) | Each cell is visited at most once — either to enqueue it or to rot it through BFS. |
Worst Case | O(m * n) | In the worst case, BFS will traverse every cell in the matrix to rot all reachable fresh oranges. |
O(m * n)
Explanation: In the worst case, the queue may hold all the oranges in the grid, especially if they're all rotten or become rotten one after another.
⬅ Previous Topic
Connected Components in a MatrixNext Topic ⮕
Flood Fill Algorithm - Graph BasedYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.