ExamAdda Logo

Rotting Oranges

Medium

You are given an m x n grid where:

  • 0 represents an empty cell.
  • 1 represents a fresh orange.
  • 2 represents 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 it is impossible for all fresh oranges to become rotten, return -1.

Example 1

Input

grid = [
    [2, 1, 1],
    [1, 1, 0],
    [0, 1, 1]
]

Output

4

Explanation

The rotten oranges spread to adjacent fresh oranges minute by minute.

It takes 4 minutes for all fresh oranges to become rotten.

Example 2

Input

grid = [
    [2, 1, 1],
    [0, 1, 1],
    [1, 0, 1]
]

Output

-1

Explanation

The fresh orange in the bottom-left corner can never be reached by a rotten orange.

Therefore, not all oranges can become rotten.

Constraints

1 <= m
n <= 10
grid[i][j] is 0
1
or 2.
0 represents an empty cell.
1 represents a fresh orange.
2 represents a rotten orange.

Hints:

Hint 1

Start by finding all rotten oranges and put them into a queue.

Hint 2

Process all rotten oranges level by level.

Each level represents one minute.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 26, 2026

Last updated

Aug 26, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output