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, кроме, наконец, и как правильно создавать пользовательские исключения.
Как генерировать случайные числа в Python
Узнайте, как генерировать случайные числа в Python. Сравните randrange, randint и генерацию равномерного числа с плавающей запятой с контролем заполнения.
Памятка по диспетчеру пакетов Python pip
Справочное руководство по командной строке для pip. Научитесь устанавливать, обновлять, удалять пакеты и зависимости Python, а также управлять ими.
Python против JavaScript: какой язык программирования лучше?
Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.