286. Walls and Gates - Detailed Explanation
Problem Statement
You are given an m × n grid (2D matrix) where:
0represents a gate.INF(2147483647) represents an empty room.-1represents a wall.
The task is to fill each empty room with the distance to its nearest gate. If a room cannot reach any gate, it should remain INF.
Constraints
- (1 \leq m, n \leq 200)
rooms[i][j]is-1,0, orINF.
Example
Input
rooms = [ [INF, -1, 0, INF], [INF, INF, INF, -1], [INF, -1, INF, -1], [0, -1, INF, INF] ]
Output
rooms = [ [3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4] ]
Explanation
- Each empty room is filled with the shortest distance to its nearest gate.
- The BFS (Breadth-First Search) traversal ensures minimum distances.
Hints
- Instead of searching from every empty room, start BFS from all gates (0s) at the same time.
- Use BFS (level-order traversal) instead of DFS, as BFS guarantees shortest paths in an unweighted grid.
- Use a queue to process cells efficiently.
Approach 1: Multi-Source BFS (Optimal Solution)
Idea
- Multi-source BFS: Start from all gates (
0s) simultaneously and spread outwards. - Why BFS? BFS ensures the shortest path is found in an unweighted graph.
- Each cell propagates its distance to its unvisited neighbors.
Algorithm
- Find all gates (
0s) and add them to a queue. - Start BFS traversal, updating empty rooms (
INF) with their shortest distance from a gate. - Stop if a cell is already visited (i.e., it has a smaller distance).
Time Complexity
- O(m × n) because each cell is processed once.
Python Implementation
Python3
Python3
. . . .
Java Implementation
Java
Java
. . . .
Step-by-Step Walkthrough (BFS Execution)
| Step | Queue (Processing Order) | Matrix After Processing |
|---|---|---|
| 1 | [(0,2), (3,0)] | Initial state (all gates in queue) |
| 2 | [(3,0) → (0,3), (1,2)] | First BFS level spread |
| 3 | [(1,2) → (2,2), (1,1)] | Spread from previous cells |
| 4 | [(2,2) → (2,0), (1,0)] | Continue BFS |
| 5 | Final State | Fully processed distances |
Common Mistakes
-
Using DFS instead of BFS
- DFS does not guarantee shortest paths in an unweighted grid.
- BFS ensures level-order traversal.
-
Not Initializing INF Properly
- Some languages may not support large values (
2147483647), so useInteger.MAX_VALUE.
- Some languages may not support large values (
-
Processing Only One Gate Instead of All
- Multi-source BFS is required to update all rooms simultaneously.
Edge Cases
| Scenario | Example Input | Expected Output |
|---|---|---|
| Only Walls | rooms = [[-1,-1],[-1,-1]] | No change |
| All Gates | rooms = [[0,0],[0,0]] | No change |
| No Gates | rooms = [[INF, INF], [INF, INF]] | No change |
| Single Column Grid | rooms = [[INF], [0], [INF]] | Updates correctly |
Alternative Variations
- Finding Longest Distance to a Gate
- Instead of BFS, use DFS with memoization.
- Find the Closest Gate from Any Point
- Modify BFS to return the distance for any query point.
Related Problems for Further Practice
| Problem | Description |
|---|---|
| [Leetcode 542: 01 Matrix] | Similar BFS approach for shortest distance to zero. |
| [Leetcode 994: Rotting Oranges] | Multi-source BFS to spread rotting oranges. |
| [Leetcode 1926: Nearest Exit from Entrance in Maze] | Finding the shortest exit using BFS. |
Final Thoughts
- BFS is the best approach because it ensures the shortest distance.
- Multi-source BFS ensures all gates spread their values simultaneously.
- Handles large grids efficiently with
O(m × n)complexity.
TAGS
leetcode
CONTRIBUTOR

Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
51. N-Queens - Detailed Explanation
Learn to solve Leetcode 51. N-Queens with multiple approaches.
362. Design Hit Counter - Detailed Explanation
Learn to solve Leetcode 362. Design Hit Counter with multiple approaches.
76. Minimum Window Substring - Detailed Explanation
Learn to solve Leetcode 76. Minimum Window Substring with multiple approaches.
465. Optimal Account Balancing - Detailed Explanation
Learn to solve Leetcode 465. Optimal Account Balancing with multiple approaches.
489. Robot Room Cleaner - Detailed Explanation
Learn to solve Leetcode 489. Robot Room Cleaner with multiple approaches.
3161. Block Placement Queries - Detailed Explanation
Learn to solve Leetcode 3161. Block Placement Queries with multiple approaches.
Related Courses
New

Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
$99

Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
$197

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
$72
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.