286. Walls and Gates - Detailed Explanation

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, 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

  1. Instead of searching from every empty room, start BFS from all gates (0s) at the same time.
  2. Use BFS (level-order traversal) instead of DFS, as BFS guarantees shortest paths in an unweighted grid.
  3. 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

  1. Find all gates (0s) and add them to a queue.
  2. Start BFS traversal, updating empty rooms (INF) with their shortest distance from a gate.
  3. 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)

StepQueue (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
5Final StateFully processed distances

Common Mistakes

  1. Using DFS instead of BFS

    • DFS does not guarantee shortest paths in an unweighted grid.
    • BFS ensures level-order traversal.
  2. Not Initializing INF Properly

    • Some languages may not support large values (2147483647), so use Integer.MAX_VALUE.
  3. Processing Only One Gate Instead of All

    • Multi-source BFS is required to update all rooms simultaneously.

Edge Cases

ScenarioExample InputExpected Output
Only Wallsrooms = [[-1,-1],[-1,-1]]No change
All Gatesrooms = [[0,0],[0,0]]No change
No Gatesrooms = [[INF, INF], [INF, INF]]No change
Single Column Gridrooms = [[INF], [0], [INF]]Updates correctly

Alternative Variations

  1. Finding Longest Distance to a Gate
    • Instead of BFS, use DFS with memoization.
  2. Find the Closest Gate from Any Point
    • Modify BFS to return the distance for any query point.
ProblemDescription
[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
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
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.
498. Diagonal Traverse - Detailed Explanation
Learn to solve Leetcode 498. Diagonal Traverse with multiple approaches.
347. Top K Frequent Elements - Detailed Explanation
Learn to solve Leetcode 347. Top K Frequent Elements with multiple approaches.
51. N-Queens - Detailed Explanation
Learn to solve Leetcode 51. N-Queens with multiple approaches.
322. Coin Change - Detailed Explanation
Learn to solve Leetcode 322. Coin Change with multiple approaches.
Related Courses
New
Grokking the AI System Design Interview course cover
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)
Discounted price for Your Region

$123

Grokking the Coding Interview: Patterns for Coding Questions course cover
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
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.