Learn DSA
Depth-First Search
Greedy Algorithms
Rotting Oranges
DESCRIPTION (credit Leetcode.com)
You are given an m x n grid representing a box of oranges. Each cell in the grid can have one of three values:
- "E" representing an empty cell
- "F" representing a fresh orange
- "R" representing a rotten orange
Every minute, any fresh orange that is adjacent (4-directionally: up, down, left, right) to a rotten orange becomes rotten.
Write a function that takes this grid as input and returns the minimum number of minutes that must elapse until no cell has a fresh orange. If it is impossible to rot every fresh orange, return -1.
Example 1:
Input:
Output: 2
Explanation:
After Minute 1: The rotting orange at grid[0][0] rots the fresh oranges at grid[0][1] and grid[1][0]. After Minute 2: The rotting orange at grid[1][0] (or grid[0][1]) rots the fresh orange at grid[1][1].
So after 2 minutes, all the fresh oranges are rotten.
Example 2:
Input:
Output: -1
Explanation:
The two adjacent oranges to the rotten orange at grid[0][0] are empty, so after 1 minute, there are no fresh oranges to rot. So it is impossible to rot every fresh orange.
Example 3:
Input:
Output: 2
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
You are given an `m x n` `grid` representing a box of oranges. Each cell in the grid can have one of three values: 1. "E" representing an empty cell 2. "F" representing a fresh orange 3. "R" representing a rotten orange Every minute, any fresh orange that is adjacent (4-directionally: up, down, left, right) to a rotten orange becomes rotten. Write a function that takes this grid as input and returns the minimum number of minutes that must elapse until no cell has a fresh orange. If it is impossible to rot every fresh orange, return -1.
Run your code to see results here
Have suggestions or found something wrong?
Explanation
Step 1: Initialize BFS Queue and Count Fresh Oranges
Step 2: BFS Traversal
Solution
from collections import dequeclass Solution:def rotting_oranges(self, grid):if not grid:return -1rows, cols = len(grid), len(grid[0])queue = deque()fresh_oranges = 0# Step 1: Initialize BFS Queue and Count Fresh Orangesfor r in range(rows):for c in range(cols):if grid[r][c] == "R":queue.append((r, c))elif grid[r][c] == "F":fresh_oranges += 1# Step 2: Perform BFS to Simulate Rotting Processdirections = [(1, 0), (-1, 0), (0, 1), (0, -1)]minutes = 0while queue and fresh_oranges > 0:minutes += 1# process all the rotten oranges at the current minutefor _ in range(len(queue)):x, y = queue.popleft()for dx, dy in directions:nx, ny = x + dx, y + dyif 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "F":grid[nx][ny] = "R"fresh_oranges -= 1queue.append((nx, ny))return minutes if fresh_oranges == 0 else -1
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.