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, or2 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
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 rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10grid[i][j] is 0, 1, or 2.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine a grid of fruits where some are fresh and some are already spoiled, and every minute the spoilage spreads to touching neighbors. The brute force approach simulates this minute-by-minute process over and over, trying every possible timeline to see how long it takes for everything to spoil.
Here's how the algorithm would work step-by-step:
def oranges_rotting(grid): row_count = len(grid) column_count = len(grid[0]) total_minutes = 0 # We must continuously simulate minute-by-minute spoilage until no more changes occur in the grid while True: grid_changed = False next_state_grid = [row[:] for row in grid] for current_row in range(row_count): for current_col in range(column_count): if grid[current_row][current_col] == 2: neighbor_offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)] for row_offset, col_offset in neighbor_offsets: neighbor_row = current_row + row_offset neighbor_col = current_col + col_offset if 0 <= neighbor_row < row_count and 0 <= neighbor_col < column_count: if grid[neighbor_row][neighbor_col] == 1: next_state_grid[neighbor_row][neighbor_col] = 2 grid_changed = True if not grid_changed: break grid = next_state_grid total_minutes += 1 # We verify if any fresh oranges survived the simulation, meaning complete spoilage was impossible for current_row in range(row_count): for current_col in range(column_count): if grid[current_row][current_col] == 1: return -1 return total_minutesInstead of checking everything separately, we can think of this like a spreading disease that moves outward in simultaneous waves from all currently rotten fruit. By tracking how many minutes it takes for the rot to reach the farthest fresh fruit, we can efficiently find the total time needed.
Here's how the algorithm would work step-by-step:
from collections import deque
def oranges_rotting(grid_matrix):
row_count = len(grid_matrix)
column_count = len(grid_matrix[0])
queue_for_rotten = deque()
fresh_orange_count = 0
elapsed_minutes = 0
for row_index in range(row_count):
for col_index in range(column_count):
if grid_matrix[row_index][col_index] == 2:
queue_for_rotten.append((row_index, col_index))
elif grid_matrix[row_index][col_index] == 1:
fresh_orange_count += 1
# Multi-source BFS requires starting simultaneously from all initially rotten oranges.
while queue_for_rotten and fresh_orange_count > 0:
for _ in range(len(queue_for_rotten)):
current_row, current_col = queue_for_rotten.popleft()
neighbor_directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for row_offset, col_offset in neighbor_directions:
neighbor_row = current_row + row_offset
neighbor_col = current_col + col_offset
if 0 <= neighbor_row < row_count and 0 <= neighbor_col < column_count:
if grid_matrix[neighbor_row][neighbor_col] == 1:
grid_matrix[neighbor_row][neighbor_col] = 2
queue_for_rotten.append((neighbor_row, neighbor_col))
fresh_orange_count -= 1
elapsed_minutes += 1
# If any fresh oranges remain unreachable, rotting the entire grid is impossible.
if fresh_orange_count > 0:
return -1
# The accumulated timer represents the total minutes needed for all oranges to rot.
return elapsed_minutes| Case | How to Handle |
|---|---|
| Grid contains only fresh oranges and zero rotten oranges | The queue starts empty with no rotten oranges, so the algorithm returns negative one if fresh oranges remain. |
| Grid contains only rotten oranges and zero fresh oranges | The initial fresh count is zero, so the algorithm immediately returns zero minutes elapsed. |
| Grid contains isolated fresh oranges completely blocked by empty cells | The multi-source breadth first search will exhaust without reaching them, leaving fresh oranges and returning negative one. |
| Minimum sized one by one grid with a single fresh orange | The initial fresh count is one and rotten count is zero, returning negative one since it can never rot. |
| Minimum sized one by one grid with a single rotten orange | The initial fresh count is zero, so the algorithm bypasses traversal and correctly returns zero minutes. |
| Grid with all empty cells and no oranges at all | Both fresh and rotten counts start at zero, allowing the algorithm to return zero minutes instantly. |
| Maximum sized grid where all fresh oranges rot in a single connected component | Breadth first search scales linearly with the number of cells visiting each grid coordinate at most once efficiently. |
| Multiple disjoint rotten oranges rotting separate clusters simultaneously | Pushing all initial rotten oranges into the queue simultaneously ensures correct parallel level order traversal. |