Typorithm · medium

Rotting Oranges

rotting-orangesgraphsmulti-source-bfsgridlevels
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Rotting Oranges

0%

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.

01

Seed BFS with all rotten cells.

02

One level processed = one minute.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Seed all rotten

Every initially rotten orange starts the BFS at once.

queue.push([r, c])

2. Count fresh

Track how many fresh oranges remain to rot.

fresh += 1

3. One minute = one level

Each BFS level is one minute of rotting.

const size = queue.length

4. Rot a neighbor

A fresh neighbor rots and the fresh count drops.

grid[nr][nc] = 2;
          fresh -= 1;

5. Reachable check

Leftover fresh oranges mean some can never rot.

return fresh === 0 ? minutes : -1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Rotting Oranges: Lesson & Practice · Typorithm | ApplyDjinn