ToolMight Logo
MediumGraphs & Matrix WalksMulti-Source BFSQueue Matrix Level Expansion

Rotting Oranges

Find minimum minutes for all fresh oranges to rot via 4-directional spreading. Compare in-place O(1)-space round simulation with optimal Multi-Source BFS.

Optimal Time
O(m * n)
Optimal Space
O(m * n)
Primary Pattern
Multi-Source BFS
Visualizer
Open Interactive View →

Problem Statement

You are given an m x n grid 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.

Examples & Constraints

Example 1
Input: grid = [ [2, 1, 1], [1, 1, 0], [0, 1, 1] ]
Output: 4
Explanation: Minute 0: [0, 0] is rotten. Minute 1: [0, 1] and [1, 0] rot. Minute 2: [0, 2] and [1, 1] rot. Minute 3: [2, 1] rots. Minute 4: [2, 2] rots.
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 reached because rotting only happens 4-directionally.
Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Simultaneous shortest-time wave propagation from multiple starting cells in a grid requires Multi-Source BFS seeding every initial source at time 0.

Core Invariant

All cells distance d from any initially rotten orange enter the queue during minute d - 1 and pop together in round d, ensuring minimum elapsed time.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Multi-Source BFS with Level SnapshotOptimal
O(m * n)O(m * n)Enqueue all initially rotten oranges simultaneously at minute 0. Expand outwards level by level: each level represents 1 minute. Decrement fresh orange count until the queue empties.
2. In-Place Timestamp Rounds (O(1) Extra Space)
O((m * n)²)O(1)Simulate each minute in-place without allocating a queue by stamping newly rotted cells with timestamp + 1 until an entire grid pass infects zero fresh oranges.

1. Multi-Source BFS with Level Snapshot

Optimal
TimeO(m * n)
SpaceO(m * n)

Enqueue all initially rotten oranges simultaneously at minute 0. Expand outwards level by level: each level represents 1 minute. Decrement fresh orange count until the queue empties.

Time ComplexityO(m * n)

Every cell in the M x N grid is visited at most once during the initial scan and at most once during the BFS queue operations.

Space ComplexityO(m * n)

The BFS queue can hold at most M x N orange coordinates in the worst case.

How It Works

Why DFS Fails for Simultaneous Spreading

In problems where multiple sources spread infection simultaneously (wildfires, virus contagion, rotting oranges), a standard DFS will trace one path deep to the end, recording incorrect time timestamps.

Instead, all rotten oranges spread their rot in parallel minute by minute. This is the definition of Multi-Source Breadth-First Search (BFS).


The Algorithm:

  1. Initial Scan:
  • Count the total number of fresh oranges (freshCount).
  • Collect the coordinates of all rotten oranges '2' and push them into a FIFO queue.
  • If freshCount == 0, return 0 immediately (no work needed).
  1. Level-by-Level Expansion:
  • Initialize minutesElapsed = 0.
  • While the queue is not empty and freshCount > 0:
  • Record levelSize = queue.size().
  • For each node in the current level:
  • Inspect all 4 neighbors: Up, Down, Left, Right.
  • If a neighbor is a fresh orange (grid[nr][nc] == 1):
  • Rot it: grid[nr][nc] = 2.
  • Decrement freshCount--.
  • Enqueue (nr, nc).
  • After finishing all nodes in the level, increment minutesElapsed++.
  1. Completion Check:
  • If freshCount == 0, return minutesElapsed.
  • If freshCount > 0, some fresh oranges were isolated and could never be reached; return -1.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Initial Scan (Minute 0)

Rotten at (0, 0). Enqueue (0, 0). Total fresh oranges = 6. minutes = 0.

State:queue = [(0, 0)]fresh = 6
Strengths
  • +Optimal O(m * n) runtime
  • +Simulates simultaneous minute-by-minute wavefront expansion directly
Trade-offs
  • -Mutates input grid values in-place unless an auxiliary visited grid is used

Reference Implementation

Complete implementation for Multi-Source BFS with Level Snapshot in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
from collections import deque
def oranges_rotting(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh = 0
# Step 1: Scan grid
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
if fresh == 0:
return 0
minutes = 0
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Step 2: Multi-source BFS
while queue and fresh > 0:
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1
if __name__ == "__main__":
grid1 = [
[2, 1, 1],
[1, 1, 0],
[0, 1, 1]
]
grid2 = [
[2, 1, 1],
[0, 1, 1],
[1, 0, 1]
]
print("grid1 minutes:", oranges_rotting(grid1))
print("grid2 minutes:", oranges_rotting(grid2))

2. In-Place Timestamp Rounds (O(1) Extra Space)

TimeO((m * n)²)
SpaceO(1)

Simulate each minute in-place without allocating a queue by stamping newly rotted cells with timestamp + 1 until an entire grid pass infects zero fresh oranges.

Time ComplexityO((m * n)²)

At most m * n rounds each scanning the m x n matrix (acceptable for constraints m, n <= 10).

Space ComplexityO(1)

Operates entirely in-place within the grid without allocating a queue.

How It Works

Zero-Queue Simulation Under Tight Memory

When grid dimensions are small or dynamic queue allocation isn't desired, encode the exact minute directly inside grid[r][c]:

  • Start at timestamp = 2 (original rotten oranges).
  • In round timestamp, scan the grid: for every cell equal to timestamp, infect adjacent 1s by setting them to timestamp + 1.
  • Repeat with timestamp++ while any fresh orange transitions; afterward, if any 1 remains, return -1, else return timestamp - 2.

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Round ts = 2

Cells equal to 2 infect adjacent 1s with value 3.

State:timestamp 2 -> marks 3s
Strengths
  • +Constant O(1) auxiliary space with zero queue allocation
Trade-offs
  • -Repeated grid scans scale poorly (`O((m*n)^2)`) if matrix dimensions grow large

Reference Implementation

Complete implementation for In-Place Timestamp Rounds (O(1) Extra Space) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def oranges_rotting_in_place(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0])
ts = 2
while True:
changed = False
for r in range(rows):
for c in range(cols):
if grid[r][c] == ts:
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = ts + 1
changed = True
if not changed:
break
ts += 1
for row in grid:
if 1 in row:
return -1
return ts - 2
Interactive Visualizer

Trace BFS & DFS mechanics in memory

Step through custom inputs in the BFS & DFS visualizer to inspect pointer updates, array shifts, and call-stack state alongside Rotting Oranges.

Open BFS & DFS visualizer

Frequently Asked Questions

Why does BFS simulate simultaneous rotting correctly while DFS fails?

BFS processes all distance-d cells together before advancing to distance d + 1. Enqueuing all initially rotten cells at minute 0 updates all concurrent spreads in lockstep; DFS follows one branch deeply and miscounts parallel steps.

Why check `fresh > 0` inside the while loop condition?

Once the last fresh orange is marked rotten, the newly enqueued cells remain in the queue for one final drain iteration. Guarding fresh > 0 stops minutes from being incremented an extra empty round.

How does Multi-Source BFS differ from running regular BFS from each source?

Running separate BFS sweeps per rotten cell takes O(k m n) time and requires taking the minimum timestamp per cell; seeding all k sources together at time 0 finishes in a single O(m * n) sweep.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • No fresh oranges initially (even if queue is empty, e.g. [[0]]) must return 0 immediately.
  • Fresh oranges exist with zero initial rotten oranges ([[1]]) returns -1 immediately.
  • Disconnected fresh orange behind empty cell 0 returns -1 after BFS finishes.

Common Bugs to Avoid

  • Writing `while (!queue.isEmpty())` without checking `fresh > 0` — adding one extra minute when the final infected oranges pop with no fresh neighbors left.
  • Starting separate BFS/DFS loops sequentially per rotten orange instead of seeding ALL initial rotten cells into the same queue at minute 0.
  • Forgetting to mark `grid[nr][nc] = 2` immediately on enqueue, allowing multiple neighbors to enqueue the same fresh cell.

Interview Follow-Up Variations

  • Walls and Gates: fill every empty room cell with exact shortest distance to any gate using identical Multi-Source BFS.
  • Shortest Bridge / As Far from Land as Possible: combine DFS component finding with Multi-Source BFS.

Related Problems

All problems
MediumGraphs & Matrix Walks

Number of Islands

Count disconnected landmasses across a 2D binary grid using connected-component traversal. Compare in-place DFS flood fill against iterative BFS.

Pattern: Depth-First Search (DFS)
O(m * n) · O(m * n)
Solve
MediumTrees & BST

Binary Tree Level Order Traversal

Group binary tree node values level-by-level from left to right. Compare FIFO queue level batching against depth-indexed DFS recursion.

Pattern: Breadth-First Search (BFS)
O(n) · O(w)
Solve