Skip to main content

Rotting Oranges

MediumPremium

You are given a 2D grid of integers representing a box of oranges. Each cell in the grid can be one of the following:

  • 0 → an empty cell
  • 1 → a fresh orange
  • 2 → a rotten orange

Every minute, any fresh orange that is adjacent (up, down, left, or right) to a rotten orange will become rotten.

Your task is to determine the minimum number of minutes required for all fresh oranges to become rotten. If it is not possible to rot all fresh oranges, return -1.

Example

Input: grid = [ [2,1,0], [0,1,1], [1,1,2] ] Output: 2

Explanation:

Minute 0 (initial): [[2 1 0] [0 1 1] [1 1 2]] Minute 1: Oranges adjacent to rotten at (0,0): (0,1) Oranges adjacent to rotten at (2,2): (1,2), (2,1) Resulting grid: [[2 2 0] [0 1 2] [1 2 2]] Minute 2: Oranges adjacent to rotten at (0,1): none (only neighbors are (0,0) rotten, (0,2) empty, (1,1) fresh) Oranges adjacent to rotten at (1,2): (1,1) Oranges adjacent to rotten at (2,1): (2,0) Resulting grid: [[2 2 0] [0 2 2] [2 2 2]]