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, or- INF.
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
Design Gurus Team
-
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
2530. Maximal Score After Applying K Operations - Detailed Explanation
Learn to solve Leetcode 2530. Maximal Score After Applying K Operations with multiple approaches.
2226. Maximum Candies Allocated to K Children - Detailed Explanation
Learn to solve Leetcode 2226. Maximum Candies Allocated to K Children with multiple approaches.
1910. Remove All Occurrences of a Substring - Detailed Explanation
Learn to solve Leetcode 1910. Remove All Occurrences of a Substring with multiple approaches.
498. Diagonal Traverse - Detailed Explanation
Learn to solve Leetcode 498. Diagonal Traverse with multiple approaches.
43. Multiply Strings - Detailed Explanation
Learn to solve Leetcode 43. Multiply Strings with multiple approaches.
532. K-diff Pairs in an Array - Detailed Explanation
Learn to solve Leetcode 532. K-diff Pairs in an Array with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
$197
New

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.