Rotting Oranges
You are given an `m x n` grid where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return `-1`. **Examples:** ```typescript orangesRotting([[2,1,1],[1,1,0],[0,1,1]]) // 4 orangesRotting([[2,1,1],[0,1,1],[1,0,1]]) // -1 orangesRotting([[0,2]]) // 0 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(m * n)
- Space complexity: O(m * n)
Multi-source BFS processes each cell at most once in O(m * n) time.
Follow-Up Questions Interviewers Ask About Rotting Oranges
- Why is BFS required instead of DFS for this problem?
Rotting spreads simultaneously in all directions minute by minute, which is the exact level-by-level behavior modeled by BFS.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.