Walls and Gates
A medium Graph problem included in Love Babbar 450. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Graph
- Sheets
- 1
- Core for
- 11 roles
- Platform
- LeetCode
The problem
Given an m x n grid where each cell is either -1 (a wall), 0 (a gate), or 2147483647 (an empty room), fill each empty room with the distance to its nearest gate. If a room cannot reach any gate, leave it as 2147483647.
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]]
- Why
- Each empty room gets the distance to its nearest gate.
Example 2
- Input
- rooms = [[-1]]
- Output
- [[-1]]
- Why
- Only a wall, nothing to fill.
Constraints
- m == rooms.length
- n == rooms[i].length
- 1 <= m, n <= 250
How to think about it
Updated 2026-09-09Searching from every empty room outward to find gates causes massive overlapping searches. Reverse perspective: start from all gates at once. Enqueue every gate cell with distance 0, then expand in waves via multi-source BFS. The first time a room is reached, the path length is guaranteed to be the shortest distance to any gate.
Approaches, worst first
BFS from each empty room
time O((m * n)^2) · space O(m * n)
Launch a breadth-first search from every cell holding 2147483647 until hitting the nearest gate. Explores redundant grid paths repeatedly, causing quadratic grid-size runtime.
Multi-source BFS from all gatesWrite this one
time O(m * n) · space O(m * n)
Scan the board once to push all cells containing 0 into a BFS queue. For each popped cell, inspect adjacent cells: if a neighbor holds 2147483647, set its value to current + 1 and enqueue it. Every empty cell is updated exactly once.
Where people lose marks · 3
- Empty rooms completely enclosed by walls (-1) must retain their initial 2147483647 value.
- Overwriting gate cells (0) or walls (-1) because neighbor checks did not strictly test for value === 2147483647.
- A grid containing zero gates should leave all empty rooms untouched without throwing errors.
The theory behind it
Graph — the ground this problem stands on. All Graph problems
What Graph is
A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.
When to reach for it
Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.
How the pattern works
First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.
What each operation costs
| Operation | Time |
|---|---|
| visit all nodes and edges via search | O(v + e) |
| topological sort using in-degree counts | O(v + e) |
| shortest path using dijkstra with a min-heap | O((v + e) log v) |
What usually goes wrong with Graph
- Adding a node to the visited set when popping from the queue instead of when pushing, which lets neighboring nodes enqueue duplicate entries and wastes memory.
- Failing to check for cycles in directed graphs when finding prerequisite orders, causing topological sort routines to hang or return incomplete lists.
- Assuming an input graph is fully connected and scanning from only a single starting node, missing disconnected islands and isolated components.
Which roles need this problem
Graph is a core topic for these 11 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 6 more roles, including Performance Engineer, Search Engineer, Information Retrieval Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Graph problems
Problem set and role mapping as of .