Walls And Gates
Detailed guide and Python implementation for the 'Walls And Gates' problem.
1. 学ぶ
The 'Walls And Gates' 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 Walls And Gates.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Walls And Gates 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 rooms initialized with these three possible values:
- -1: A wall or an obstacle.
- 0: A gate.
- INF (represented by 2147483647): An empty room.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
Write a function wallsAndGates(rooms: List[List[int]]) -> List[List[int]] that returns the modified rooms grid.
- •m == len(rooms)
- •n == len(rooms[i])
- •1 <= m, n <= 250
- •rooms[i][j] is -1, 0, or 2147483647
例
rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
The empty rooms are filled with the shortest distance to their nearest gate.
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 walls_and_gates_opt(rooms):
ROWS, COLS = len(rooms), len(rooms[0])
q = deque()
for r in range(ROWS):
for c in range(COLS):
if rooms[r][c] == 0: q.append((r, c))
while q:
r, c = q.popleft()
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 rooms[nr][nc] == 2147483647:
rooms[nr][nc] = rooms[r][c] + 1
q.append((nr, nc))ブルート フォース コード (スポイラーガード付き)
ブルート フォース コード (スポイラーガード付き)
def walls_and_gates_brute(rooms):
ROWS, COLS = len(rooms), len(rooms[0])
def dfs(r, c, dist):
if r < 0 or r == ROWS or c < 0 or c == COLS or rooms[r][c] < dist:
return
rooms[r][c] = dist
dfs(r + 1, c, dist + 1)
dfs(r - 1, c, dist + 1)
dfs(r, c + 1, dist + 1)
dfs(r, c - 1, dist + 1)
for r in range(ROWS):
for c in range(COLS):
if rooms[r][c] == 0:
dfs(r, c, 0)Algorithm 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 Try/Except とエラー処理
Python スクリプトがクラッシュしないようにします。 try、excel、finally ブロックと、カスタム例外を適切に発生させる方法について学びます。
Python で乱数を生成する方法
Python で乱数を生成する方法を学びます。 randrange、randint、およびuniform floatの生成とシード制御を比較します。
Python pip パッケージ マネージャーのチートシート
pip のコマンドライン リファレンス ガイド。 Python パッケージと依存関係のインストール、アップグレード、アンインストール、管理について学びます。
Python と JavaScript: どちらのプログラミング言語が最適ですか?
Python と JavaScript の包括的な比較。構文の違い、パフォーマンス、使用例 (バックエンドとフロントエンド)、およびコーディング例を調べます。