Practice Problem

Rotting Oranges

Difficulty: Medium

Given a grid where cells contain fresh oranges, rotten oranges, or are empty, determine the minimum time for all fresh oranges to rot via adjacency spreading.

Rotting Oranges

You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing 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 this is impossible, return -1.

Examples

Example 1:

Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Explanation: The rotten orange at (0,0) spreads to adjacent
fresh oranges each minute. After 4 minutes, all oranges are rotten.

Example 2:

Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange at (2,2) can never be reached because
it is isolated from the rotten orange.

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: There are no fresh oranges, so 0 minutes are needed.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2

Expected Complexity

  • Time: O(m * n)
  • Space: O(m * n)
MEDIUM
Graphs
BFS
Multi-Source BFS
Islands / Flood Fill
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium