#994

Rotting Oranges

MediumMulti-source BFSHas vizArrayBFSMatrix

Problem

  • 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.

Example 1

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

Output: 4

It takes 4 minutes for all fresh oranges to rot.

Example 2

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

Output: -1

The bottom-left orange never rots.

Example 3

Input: grid = [[0,2]]

Output: 0

No fresh oranges.

Constraints

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

Explanation

Rotting Oranges is a Medium interview problem tagged [Array, BFS, Matrix]. The winning approach is typically **Multi-source BFS**.

Intuition

Simultaneous infection/flow frontiers stay O(mn).

Approach

Enqueue all sources at once so distance expands in parallel waves.

  1. Find all sources.
  2. BFS together.
  3. Update neighbor distances/states.
  4. Read final grid/count.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateMulti-source BFS

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Multi-source BFS), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #994 Rotting Oranges as understood when the pattern clicks.