A crate of oranges is laid out as a grid, grid. Each cell holds 0 (no orange), 1 (a fresh orange) or 2 (a rotten orange).
Rot spreads once a minute: every fresh orange that shares a side with a rotten one (up, down, left or right, never diagonally) turns rotten at the end of that minute. Return how many minutes pass until no fresh orange is left. If some fresh orange can never be reached, return -1.
Example 1
Input: grid = [[1, 1, 0],
[2, 1, 1],
[0, 0, 1]]
Output: 3
Why: the bottom right orange is three steps from the rotten one2 more examples and the constraints
Example 2
Input: grid = [[2, 1, 0],
[0, 1, 1],
[1, 0, 0]]
Output: -1
Why: the orange in the bottom left has no neighbour at allExample 3
Input: grid = [[0, 2, 0]] Output: 0 Why: there is no fresh orange, so no time has to pass
Constraints
- 1 ≤ rows, columns ≤ 10
- Every cell is 0, 1 or 2
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Simulate minute by minuteO((m·n)²)
- Multi-source BFSO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10 × 10 grid with a long path | Verdict |
|---|---|---|---|
| Simulate minute by minute | O((m·n)²) | Easy to explain, rescans all | |
| Multi-source BFS | O(m·n) | Best; each cell once |
m = rows, n = columns.
Edge cases to test
- No fresh oranges. The answer is 0, even if there is no rotten orange either.
- Fresh oranges but nothing rotten. Nothing can start the rot, so the answer is -1.
- An orange cut off by empty cells. It never rots: the fresh count stays above 0 and the answer is -1.
- Diagonal neighbours. [[2, 0], [0, 1]] is -1: rot does not jump corners.
- Several rotten oranges. They all spread at the same time; [[2, 1, 1, 1, 2]] takes 2 minutes, not 4.
Common mistakes
- Running BFS from one rotten orange at a time, which overcounts the minutes.
- Counting BFS rounds even when the last round rots nothing, so the answer is one too big.
- Forgetting to check for fresh oranges left over, and returning a time instead of -1.
How to talk through it
- 1Clarify. Do diagonals count? What if there are no fresh oranges, or no rotten ones?
- 2Give the simulation. Rescan the grid every minute and rot what touches rot; say why that repeats work.
- 3Name the BFS. Rot spreads one layer per minute from every rotten orange at once: a BFS with many sources.
- 4Code it with a fresh count. Seed the queue with all rotten oranges, count fresh ones, and lower the count as they rot.
- 5Test out loud. Run the cut-off orange, the empty grid and the two-sources case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?