AlgoInsight

DSA problem

Rotting Oranges

MediumBreadth First Search (BFS)Pattern: Breadth First Search (BFS)top75FreeAmazonMicrosoftGoogleMetaApple

You are given an m x n grid where each cell contains exactly one of three values: 0 for an empty cell, 1 for a fresh orange, and 2 for a rotten orange. Every minute any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten itself.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If it is impossible for every fresh orange to become rotten — for example because a fresh orange is unreachable from any rotten one — return -1.

This is the canonical multi-source BFS pattern. All initially rotten oranges decay simultaneously, so they all start at "time = 0". Run BFS where the source set is every rotten orange at once; each BFS level corresponds to one minute elapsing. The level reached when the queue empties is the minute the last orange rots.

The optimal approach first scans the grid to enqueue every rotten orange and count the fresh ones. Then it BFS-expands by levels: each iteration of the outer loop is one minute; we pop the entire current level, rot every fresh 4-neighbour, decrement the fresh count, and enqueue the newly rotten cells. After the queue is empty, if fresh remains the answer is -1; otherwise it is the number of completed levels (subtract one if we counted the initial level as a minute). This runs in O(m * n) time and O(m * n) space.

Examples

Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Explanation: Minute 1 rots (0,1) and (1,0). Minute 2 rots (1,1). Minute 3 rots (2,1). Minute 4 rots (2,2). All fresh oranges are now rotten in 4 minutes.
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The bottom-left fresh orange at (2,0) has no path of fresh neighbours to a rotten orange, so it can never rot.
Example 3
Input: grid = [[0,2]]
Output: 0
Explanation: There are no fresh oranges to begin with, so zero minutes are needed.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bfsgridmulti-source-bfsmatrix

Browse all DSA problems