Rotting Oranges
Detailed guide and Python implementation for the 'Rotting Oranges' problem.
1. Узнать
The 'Rotting Oranges' problem is a key challenge in the Graphs section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Rotting Oranges.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Rotting Oranges carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Постановка задачи
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
Примеры
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 input structures
- Single element inputs
- Large numerical bounds
Готовы решить?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Интервью: идеи и вариации
Разбивка анализа сложности
Почему время: Directly evaluates all possibilities.
Почему космос: Uses standard local memory.
Почему время: Optimized paths reduce total operations.
Почему космос: May trade memory for speed.
Оптимизированный код Python для решения
Оптимизированный код Python для решения
from collections import deque
def oranges_rotting_opt(grid):
q = deque()
time, fresh = 0, 0
ROWS, COLS = len(grid), len(grid[0])
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 1: fresh += 1
if grid[r][c] == 2: q.append((r, c))
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
while q and fresh > 0:
for i in range(len(q)):
r, c = q.popleft()
for dr, dc in directions:
row, col = r + dr, c + dc
if 0 <= row < ROWS and 0 <= col < COLS and grid[row][col] == 1:
grid[row][col] = 2
q.append((row, col))
fresh -= 1
time += 1
return time if fresh == 0 else -1Код грубой силы (спойлер защищен)
Код грубой силы (спойлер защищен)
def oranges_rotting_brute(grid):
rows, cols = len(grid), len(grid[0])
time = 0
while True:
to_rot = []
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
for dr, dc in [[1,0], [-1,0], [0,1], [0,-1]]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
to_rot.append((nr, nc))
if not to_rot: break
for r, c in to_rot: grid[r][c] = 2
time += 1
for row in grid:
if 1 in row: return -1
return timeAlgorithm Pattern Checklist
When dealing with Graphs data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Graphs problem properties apply.
Связанные вопросы
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Рекомендуемые ресурсы Python
Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.
Циклы Python
Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.
Как отсортировать список в Python
Узнайте, как сортировать список в Python с помощью метода sort() и функции sorted(). Ознакомьтесь с примерами пользовательской сортировки ключей и обратного порядка.
Шпаргалка по строковым методам Python
Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.
Python против JavaScript: какой язык программирования лучше?
Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.