The Rotting Oranges problem involves a 2D grid representing a box of oranges. Each cell in the grid can either be empty (represented by 0), contain a fresh orange (1), or contain a rotten orange (2). Every minute, any fresh orange that is directly adjacent to a rotten orange (horizontally or vertically) becomes rotten. The goal is to determine the minimum number of minutes required for all fresh oranges to become rotten. If it is impossible to rot all the oranges, the function should return -1
.
To efficiently solve the Rotting Oranges problem, we use a Breadth-First Search (BFS) approach. This is ideal for problems involving spreading or expansion, such as traversing levels in a grid. By modeling the rotting process minute by minute, we simulate how rot spreads from initially rotten oranges to adjacent fresh ones.
First, we scan the grid and collect all positions of the rotten oranges. These positions act as the starting points for the BFS. We also count how many fresh oranges exist at the start. This step ensures we know how many oranges need to be rotted for the final result to be valid.
Next, we perform a level-by-level BFS traversal using a queue. For each level (each minute), we process all rotten oranges currently in the queue. For each orange, we examine its four neighboring cells—up, down, left, and right. If a neighbor contains a fresh orange, we mark it as rotten and add it to the queue for the next round of processing. We also decrement the count of fresh oranges.
The BFS continues until there are no more oranges to process. After BFS finishes, if there are still fresh oranges remaining, it means not all could be reached, so we return -1
. Otherwise, we return the number of minutes it took to rot all the oranges.
The time complexity of this algorithm is O(m * n)
where m
and n
are the number of rows and columns in the grid. This is because we visit each cell at most once. The space complexity is also O(m * n)
due to the space required for the queue and the grid itself.
BFS is particularly well-suited for this problem because it naturally models the spreading of an effect (in this case, rot) across a space over time. Each level in BFS represents a unit of time—exactly what we need to track minutes as oranges rot. Unlike depth-first search, which dives deep into one path, BFS ensures that all adjacent oranges rot simultaneously at each time step.
Don’t forget to handle edge cases, such as when there are no fresh oranges at the start—this should return 0
immediately. Also, make sure not to rot the same orange multiple times. Marking visited oranges right away ensures we avoid infinite loops or redundant processing.