Leetcode #286: Walls and Gates
In this guide, we solve Leetcode #286 Walls and Gates in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Breadth-First Search, Array, Matrix
Intuition
We need level-by-level exploration or shortest steps, which is ideal for BFS.
A queue naturally models the frontier of the search.
Approach
Push initial nodes into a queue and expand in layers.
Track visited nodes to prevent cycles.
Steps:
- Initialize queue with start nodes.
- Process level by level.
- Track visited nodes.
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
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.