Data Structures & Algorithms Queues & Deques
💡
Exercise 80

Rotting Oranges 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

You have a grid where 0 = empty, 1 = fresh orange, 2 = rotten orange. Every minute, fresh oranges adjacent (4-directionally) to rotten ones become rotten. Return the minimum minutes until no fresh orange remains, or -1 if impossible.

grid = [[2,1,1], [1,1,0], [0,1,1]] # Minute 0: Only (0,0) is rotten # Minute 1: (0,1) and (1,0) rot # Minute 2: (0,2), (1,1) rot # Minute 3: (2,1) rots # Minute 4: (2,2) rots # Answer: 4 minutes

This is a classic multi-source BFS problem:

  • Start by adding ALL rotten oranges to the queue (multi-source)
  • BFS level by level — each level = 1 minute
  • Each rotten orange spreads to 4 neighbors (up/down/left/right)
  • If fresh oranges remain after BFS, return -1

Think of it as a flood fill spreading from multiple sources simultaneously. Time: O(m×n).

📋 Instructions
Implement `oranges_rotting(grid)` using multi-source BFS. Test with the provided grid.
First, find all rotten oranges and count fresh ones. Add all rotten to a deque. BFS: for each level, spread rot to 4 neighbors. Track minutes. After BFS, if fresh_count > 0, return -1.
🧪 Test Cases
Input
oranges_rotting(grid)
Expected
4
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.