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 でリストを並べ替える方法
sort() メソッドとsorted() 関数を使用して、Python でリストを並べ替える方法を学びます。カスタムキーの並べ替えと逆順の例をご覧ください。
Python 文字列メソッドのチートシート
Python 文字列操作の完全なリファレンス ガイド。文字列プロパティの書式設定、検索、分割、置換、チェックをマスターします。
Python と JavaScript: どちらのプログラミング言語が最適ですか?
Python と JavaScript の包括的な比較。構文の違い、パフォーマンス、使用例 (バックエンドとフロントエンド)、およびコーディング例を調べます。