Question and Answer from L4-M1
from collections import deque
import copy
def rotting_oranges(grid):
"""
Calculates the minimum time required for all fresh oranges to become rotten in a grid.
"""
if not grid or not grid[0]:
return "All oranges can become rotten in 0 time frames."
m = len(grid)
n = len(grid[0])
queue = deque()
fresh_count = 0
# Initialize the queue with rotten oranges and count fresh oranges
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append((i, j, 0))
elif grid[i][j] == 1:
fresh_count += 1
# If there are no fresh oranges, time required is 0
if fresh_count == 0:
return "All oranges can become rotten in 0 time frames."
# If there are fresh oranges but no rotten ones, it's impossible
if not queue:
return "All oranges cannot rot"
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
max_time = 0
# Start BFS
while queue:
x, y, time = queue.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
# Check for valid and fresh neighbors
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1:
grid[nx][ny] = 2 # Rot the orange
fresh_count -= 1
max_time = max(max_time, time + 1)
queue.append((nx, ny, time + 1))
# Check if all fresh oranges were reached
if fresh_count == 0:
return f"All oranges can become rotten in {max_time} time frames."
else:
return "All oranges cannot rot"
m, n = map(int, input().split())
grid = []
for _ in range(m):
row = list(map(int, input().split()))
grid.append(row)
print(rotting_oranges(grid))