Walls And Gates
Detailed guide and Python implementation for the 'Walls And Gates' problem.
1. Concept Overview
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.
Problem Statement
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
Examples
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
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
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))Brute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
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.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Try/Except & Error Handling
Prevent your Python scripts from crashing. Learn try, except, finally blocks and how to raise custom exceptions properly.
How to Generate Random Numbers in Python
Learn how to generate random numbers in Python. Compare randrange, randint, and uniform float generation with seeding control.
Python pip Package Manager
Command-line reference guide for pip. Learn to install, upgrade, uninstall, and manage Python packages and dependencies.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.