286. Walls and Gates - Detailed Explanation
Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!
Problem Statement
You are given an m × n
grid (2D matrix) where:
0
represents a gate.INF
(2147483647
) represents an empty room.-1
represents 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
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
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.

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