Rotting Oranges
Learn how to solve the 'Rotting Oranges' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
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.
- •m == len(grid)
- •n == len(grid[i])
- •1 <= m, n <= 10
- •grid[i][j] is 0, 1, or 2
Examples
grid = [[2,1,1],[1,1,0],[0,1,1]]
4
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.
grid = [[2,1,1],[0,1,1],[1,0,1]]
-1
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?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.