#994

Rotting Oranges

Medium Multi-source BFS

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Every minute, rotten oranges rot their fresh 4-directional neighbours. Return the minutes until no fresh orange is left, or -1 if that never happens.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: minutes until every orange is rotten, or -1.

Why this works: all rotten oranges spread at once, so start BFS from all of them together; each BFS level is one minute.

Example: 2 1 1 / 1 1 0 / 0 1 1

minute 1, 2, 3, 4 → all rotten → 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Running a separate BFS from each rotten orange — wrong timing and slower.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n).
  • Space: O(m·n).
Topic: Graphs
🎬 Episodes 74–85: video coming soon