Skip to main content
Back to problems
Leetcode
Medium
Matrices
Graphs
Queues
Amazon
Microsoft
Rotting Oranges

Given a grid of fresh and rotten oranges, determine how many minutes it takes for all fresh oranges to rot as rot spreads to adjacent cells each minute.

Acceptance 100%
Problem Statement

You are given an m×nm \times n grid representing a box of oranges. Each cell contains one of three values:

  • 0 — empty cell
  • 1 — fresh orange
  • 2 — rotten orange

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes needed for all oranges to become rotten.

If it is impossible for some fresh oranges to rot, return -1.

The process happens simultaneously each minute, so newly rotten oranges can only affect other oranges in the next minute.

Input Format

  • A 2D integer grid grid of size m x n
  • grid[i][j] is one of 0, 1, or 2

Output Format

  • Return an integer: the minimum minutes needed for all fresh oranges to rot, or -1 if impossible.

Constraints

  • 1m,n1 \le m, n
  • Cell values are limited to 0, 1, and 2
  • Rot spreads only in 4 directions: up, down, left, right
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

4

Explanation

Minute 0: the top-left orange is rotten. Minute 1: its adjacent fresh oranges rot. Minute 2 and onward: the rot continues spreading until all fresh oranges are rotten after 4 minutes.

Example 2

Input

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

Output

-1

Explanation

Some fresh oranges are isolated by empty cells and can never be reached by rot.

Show 1 more example

Example 3

Input

grid = [[0,2]]

Output

0

Explanation

There are no fresh oranges to rot, so the answer is 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.