Matrix BFS: Rotting Oranges
Read a little, play a little. No scary maths, and no rush.
Fruit that spoils its neighbors
A grid of oranges: rotten ones infect adjacent fresh ones each minute. How long until everything rots — or prove some orange is unreachable? This is BFS wearing a work uniform: instead of one start, every rotten orange starts simultaneously, and each BFS level equals one minute of spread.
Multi-source BFS: all starts at once
from collections import deque
def oranges(g):
R, C = len(g), len(g[0])
q = deque(
[(r, c) for r in range(R) for c in range(C) if g[r][c] == 2]
)
fresh = sum(v == 1 for row in g for v in row)
mins = 0
while q and fresh:
for _ in range(len(q)): # one whole minute:
r, c = q.popleft()
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == 1:
g[nr][nc] = 2 # it rots now
fresh -= 1
q.append((nr, nc))
mins += 1
return mins if fresh == 0 else -1
Two details carry the solution: seeding the queue with all rotten cells (multi-source), and only ticking mins when a level actually rotted something (while q and fresh guards the empty final level).
The pattern family
Same skeleton solves walls and gates (gates infect distance outward), shortest bridge between islands, and 01-matrix distances. Whenever spread happens everywhere at once, seed every source and count levels.
Traced on a small grid
2 1 1
1 1 0
0 1 1
Here 2 is rotten, 1 is fresh, and 0 is empty.
- Minute 1: the two fresh oranges touching the top-left corner rot.
- Minute 2: the top-right orange and the center rot.
- Minute 3: the bottom-middle orange rots.
- Minute 4: the bottom-right orange rots.
No fresh oranges remain, so the answer is 4. Each minute is exactly one level of the BFS.
Why one BFS, not many
You could run a separate BFS from each rotten orange and combine the results, but with k rotten oranges that is k times the work. Seeding all of them into one queue at the start runs a single BFS over the grid, O(rows × columns) in total. It also gives the right answer directly: each fresh orange rots at the time it is reached from its nearest rotten source, which is exactly what simultaneous spread means.
Edge cases to check aloud
- No fresh oranges at all: the answer is 0, and the loop never runs.
- A fresh orange walled off by empty cells: it is never reached, so
freshstays above zero and the answer is −1. - Fresh oranges but no rotten ones: nothing can spread, so −1.
Other neighbor rules
Some problems let spread happen diagonally too. Only the list of directions changes: use all eight combinations of −1, 0, and +1 instead of four. Everything else, the queue, the levels, the counting, stays the same.
Changing the grid in place
The solution marks oranges rotten by editing the grid, which doubles as the visited set. If the input must not be modified, copy it first or keep a separate visited set, and say which you are doing.
Where this shows up outside interviews
Multi-source BFS models anything that spreads outward from several places at once: the distance from every street corner to its nearest fire station, how many network hops a message needs to reach each machine, or a game map showing how far each tile is from the closest exit. Whenever the question is "how far is everything from the nearest source," seed every source and walk the levels.
Remember this
- Multi-source BFS: many starts, one queue, levels = time steps.
- Track remaining targets; leftovers at the end mean unreachable (-1).
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
End of Next Level (Brief)
Take the section checkpoint
A short mixed quiz on all 4 chapters, to check you are ready to move on.
Related chapters
Spotted a mistake or want a topic covered? Report an issue