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, or2 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.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]] Output: 4
Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.Problem Overview: You are given a grid where 0 represents empty cells, 1 fresh oranges, and 2 rotten oranges. Every minute, rotten oranges infect their 4-directionally adjacent fresh neighbors. The task is to compute the minimum number of minutes required until no fresh oranges remain, or return -1 if some oranges can never rot.
Approach 1: Breadth-First Search (Multi-Source BFS) (Time: O(m*n), Space: O(m*n))
This problem is essentially a level-by-level spread across a grid, which maps perfectly to Breadth-First Search. Start by pushing all initially rotten oranges into a queue. Each BFS layer represents one minute. For every rotten orange, check its four neighbors and convert any fresh orange to rotten, pushing it into the queue for the next minute.
The key insight is treating all rotten oranges as simultaneous starting points (multi-source BFS). Instead of simulating minute-by-minute scanning of the entire grid, BFS only processes cells that actually change state. Track the remaining fresh oranges during traversal; if any remain after BFS finishes, return -1. This approach runs in O(m*n) time because each cell is processed at most once and uses O(m*n) space for the queue in the worst case.
The grid itself behaves like an implicit graph where each cell connects to its four neighbors. Problems involving propagation across a matrix or layered expansion usually signal BFS as the optimal strategy.
Approach 2: DFS with Memoization (Time: O(m*n), Space: O(m*n))
An alternative approach computes the minimum time for each fresh orange to become rotten using depth-first search. Starting from rotten oranges, DFS explores neighbors recursively while memoizing the earliest minute each cell becomes infected. If a DFS path reaches a fresh orange with a shorter infection time than previously recorded, update and continue exploring.
This method treats the grid like a recursive propagation problem on a graph built from the array representation. Memoization prevents recomputing infection times for cells that already have an optimal value. While the theoretical time complexity remains O(m*n), recursion overhead and repeated neighbor checks make it less intuitive than BFS.
DFS works but requires careful handling of cycles and time comparisons to avoid unnecessary recursion. Because the infection spreads simultaneously from multiple sources, DFS does not naturally model the "minute-by-minute" process the way BFS does.
Recommended for interviews: Multi-source BFS is the expected solution. It directly models the spread of rot as a wave expanding outward each minute and guarantees optimal timing naturally through BFS levels. Mentioning a brute-force simulation or DFS idea shows understanding, but implementing the BFS queue approach demonstrates strong grasp of graph traversal on grids.
This approach uses BFS to simulate the rotting process of the oranges. We start with all initially rotten oranges and spread the rot to the 4-adjacent fresh oranges, time step by time step. We use a queue to implement BFS, where each element in the queue represents a rotten orange at a specific time. The key idea is that in one minute, all current rotten oranges will rot their 4-directionally adjacent fresh oranges.
We initialize a queue with the position of all rotten oranges (value 2) and their corresponding time, which is 0 initially. We also keep a count of fresh oranges. For each iteration, we process rotten oranges, spread the rot, and keep track of the time taken for each step. If at the end there are still fresh oranges left, we return -1.
Python
JavaScript
Time Complexity: O(m * n), where m and n are the number of rows and columns in the grid. Each cell is processed at most once.
Space Complexity: O(m * n) for the queue, in the worst case.
Instead of using BFS, this approach converts the problem to a depth-first search with memoization. By examining from each fresh orange, one can determine its minimum time to rot by considering all possible paths of infection.
This solution uses depth-first search (DFS) and memoization to find the shortest path from a fresh orange to a rotten one. Each fresh orange recursively checks all possible paths to rotten oranges, updating the minimum time via memoization.
Time Complexity: O(m * n), as each cell is processed recursively.
Space Complexity: O(m * n) because of the memoization table and the call stack in recursion.
First, we traverse the entire grid once, count the number of fresh oranges, denoted as cnt, and add the coordinates of all rotten oranges to the queue q.
Next, we perform a breadth-first search. In each round of the search, we let all the rotten oranges in the queue rot the fresh oranges in four directions, until the queue is empty or the number of fresh oranges is 0.
Finally, if the number of fresh oranges is 0, we return the current round number, otherwise, we return -1.
The time complexity is O(m times n), and the space complexity is O(m times n). Where m and n are the number of rows and columns of the grid, respectively.
Python
Java
C++
Go
TypeScript
Rust
JavaScript
| Approach | Complexity |
|---|---|
| Breadth-First Search (BFS) | Time Complexity: O(m * n), where m and n are the number of rows and columns in the grid. Each cell is processed at most once. |
| DFS with memoization | Time Complexity: O(m * n), as each cell is processed recursively. |
| BFS | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Multi-Source Breadth-First Search | O(m*n) | O(m*n) | Best general solution for grid propagation problems where states spread level-by-level. |
| DFS with Memoization | O(m*n) | O(m*n) | Useful when modeling infection time recursively or exploring alternative graph traversal strategies. |
Rotting Oranges - Leetcode 994 - Python • NeetCode • 168,375 views views
Watch 9 more video solutions →Practice Rotting Oranges with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor