You are given grid with fresh and rotten oranges. Find minimum time for all oranges to rot.
Approach
Multi-source BFS from all rotten oranges, tracking minutes per layer.
Time O(mn)Space O(mn)
How it works
1Seed the queue with every rotten orange.
2Each BFS layer rots neighbours: one minute.
3Leftover fresh means impossible: -1.
Sample input / output
Input:
3
2 1 1
1 1 0
0 1 1
Output:
4
Constraints
1 <= m, n <= 10; cells 0/1/2.
Solution — read it, then walk it
Time O(mn)Space O(mn)Loops 5Branches 5Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
start / end
statement
condition
loop
returns
definition
1/37
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits →