Top 150 InterviewEasy

Rotting Oranges

Detailed guide and Python implementation for the 'Rotting Oranges' problem.

Problem Statement

Easy

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.

Write a function orangesRotting(grid: List[List[int]]) -> int.

Constraints
  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2

Examples

Example 1
Input
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output
4
Explanation

Minute 0: rotten at (0,0). Fresh at (0,1), (0,2), (1,0), (1,1), (2,1), (2,2). Minute 1: fresh at (0,1) and (1,0) rot. Minute 2: fresh at (0,2) and (1,1) rot. Minute 3: fresh at (2,1) rot. Minute 4: fresh at (2,2) rot.

Example 2
Input
grid = [[2,1,1],[0,1,1],[1,0,1]]
Output
-1
Explanation

The orange in the bottom-left corner (row 2, column 0) is never adjacent to a rotten orange, so it stays fresh.

Need a Hint?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.