MediumNo. 0286LeetCode Premium
Walls and Gates — LeetCode 286 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Breadth-First Search, Array, Matrix
- On a study list
- NeetCode 150
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle.
Example
- Input
- rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
- Output
- [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Python solution
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
m, n = len(rooms), len(rooms[0])
inf = 2**31 - 1
q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0])
d = 0
while q:
d += 1
for _ in range(len(q)):
i, j = q.popleft()
for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and rooms[x][y] == inf:
rooms[x][y] = d
q.append((x, y))Complexity
- Time
- O(V+E)
- Space · auxiliary
- O(V)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 286. Walls and Gates is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0864 | Shortest Path to Get All Keys | Hard |
| 0909 | Snakes and Ladders | Medium |
| 0994 | Rotting Oranges | Medium |
| 1091 | Shortest Path in Binary Matrix | Medium |
| 1210 | Minimum Moves to Reach Target with Rotations | Hard |
| 1293 | Shortest Path in a Grid with Obstacles Elimination | Hard |
Frequently asked questions
- How hard is LeetCode 286. Walls and Gates?
LeetCode 286. Walls and Gates is rated Medium on LeetCode.
- What is the time complexity of LeetCode 286. Walls and Gates?
The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 286. Walls and Gates?
The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 286. Walls and Gates cover?
LeetCode 286. Walls and Gates is tagged Breadth-First Search, Array and Matrix on LeetCode.
- Is LeetCode 286. Walls and Gates a premium problem?
Yes. LeetCode 286. Walls and Gates is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.