Skip to main content

Walls and Gates - Solution & Explanation

MediumPremiumFree on FleetCodeArrayBreadth-First SearchMatrix5 min readAsked at: Amazon, Microsoft, Meta +8
Practice this problem

Problem Statement

You are given an m x n grid rooms initialized with these three possible values.

  • -1 A wall or an obstacle.
  • 0 A gate.
  • INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

 

Example 1:

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

Example 2:

Input: rooms = [[-1]]
Output: [[-1]]

 

Constraints:

  • m == rooms.length
  • n == rooms[i].length
  • 1 <= m, n <= 250
  • rooms[i][j] is -1, 0, or 231 - 1.

Approach Overview

Problem Overview: You are given a 2D grid representing rooms, gates, and walls. Each empty room must be filled with the distance to its nearest gate. Walls block movement, and if a gate cannot be reached the value remains unchanged.

This is fundamentally a shortest-path problem on a grid. Each move to an adjacent cell (up, down, left, right) costs one step. The goal is to compute the minimum distance from every empty room to the closest gate efficiently.

Approach 1: BFS From Every Empty Room (Brute Force) (Time: O((mn)^2), Space: O(mn))

For every empty room, run a Breadth-First Search until you hit a gate. BFS guarantees the first gate found is the closest because it expands level by level. However, you repeat the same exploration for many cells, causing massive overlap. On an matrix with m * n cells, each BFS can scan most of the grid, leading to quadratic behavior. This approach works for small grids but times out on larger inputs.

Approach 2: DFS From Each Gate (Time: O(mn), Space: O(mn))

Another idea is to start from each gate and spread distances using depth-first search. The DFS recursively explores neighbors while tracking distance. When reaching a room, update it only if the current path gives a shorter distance than the stored value. This avoids recomputing from every empty room, but DFS may revisit cells multiple times and recursion depth can grow large. While workable, it is harder to control updates and less predictable than BFS for shortest-path problems.

Approach 3: Multi-Source BFS From All Gates (Optimal) (Time: O(mn), Space: O(mn))

The optimal solution reverses the perspective: start BFS simultaneously from all gates. Push every gate into a queue with distance 0, then expand outward level by level. When visiting neighbors, update an empty room only if its value is still INF, then set it to current_distance + 1 and enqueue it. Because BFS expands in layers, the first time a room is reached is guaranteed to be the shortest distance to any gate.

This approach visits each cell at most once. Every expansion processes four neighbors and updates the grid directly. The algorithm runs in O(mn) time and uses O(mn) space for the queue in the worst case. The logic mirrors classic shortest path problems on grids and heavily relies on queue-based BFS traversal over an array-backed matrix.

Recommended for interviews: Multi-source BFS from all gates. It demonstrates strong intuition about reversing the search direction to avoid redundant work. Mentioning the brute-force BFS shows you understand the baseline, but implementing the multi-source BFS shows you recognize optimal graph traversal patterns used in grid shortest-path problems.

Solution

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
BFS From Every Empty RoomO((mn)^2)O(mn)Conceptual baseline or when grid size is very small
DFS From Each GateO(mn)O(mn)Alternative propagation method but harder to control updates
Multi-Source BFS From All GatesO(mn)O(mn)Optimal approach for shortest distance in grid with multiple sources

Video Solution

Walls and Gates - Multi-Source BFS - Leetcode 286 - Python • NeetCode • 139,075 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Walls and Gates easy or hard?
Walls and Gates is generally considered a medium difficulty problem. The grid traversal itself is straightforward, but the key insight is reversing the search and running BFS from all gates instead of each empty room.
Walls and Gates Python/Java solution
Most solutions implement multi-source BFS using a queue. Gates are first pushed into the queue, then neighbors are explored in four directions while updating distances. This approach works the same across Python, Java, C++, and Go with O(mn) time complexity.
How to solve Walls and Gates in O(n)?
Treat all gates as starting nodes and perform a multi-source BFS. Insert every gate into a queue with distance 0, then expand level by level updating adjacent empty rooms with distance +1. Because each cell is processed once, the runtime becomes O(mn), which is linear in the number of grid cells.
What is the best approach for Walls and Gates?
The best approach is multi-source Breadth-First Search (BFS). Instead of running BFS from every empty room, push all gates into the queue first and expand outward. BFS guarantees the first time a room is reached is the shortest distance to a gate. This reduces the complexity to O(mn).
Is Walls and Gates asked at Google/Amazon/Meta?
Walls and Gates is a common grid BFS interview problem and has appeared in interviews at companies like Google, Amazon, and Meta. It tests understanding of shortest path traversal, BFS layering, and matrix traversal patterns frequently used in system and graph problems.
What data structure is used in Walls and Gates?
The core data structure is a queue used for Breadth-First Search. The grid itself acts as the state storage where distances are updated in-place. BFS ensures level-by-level expansion so each room gets the minimum distance to a gate.
What is the time complexity of Walls and Gates?
The optimal solution runs in O(mn) time where m and n are the grid dimensions. Each cell is visited at most once during the BFS traversal. Every step processes up to four neighbors, making the algorithm linear with respect to the number of cells.

Ready to solve this problem?

Practice Walls and Gates with our built-in code editor and test cases.

Practice on FleetCode