Walls And Gates
Detailed guide and Python implementation for the 'Walls And Gates' problem.
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.
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.