medium Walls and Gates
Problem Statement
You are given a grid of size m x n filled with three possible values:
-1representing a wall or an obstacle.0representing a gate.2147483647(INF) representing an empty room.
Fill each empty room with the distance to its nearest gate. If an empty room cannot reach any gate, it should remain 2147483647.
Examples
Example 1
- Input:
[[2147483647, -1, 0], [2147483647, 2147483647, 2147483647], [2147483647, -1, 2147483647]] - Expected Output:
[[4, -1, 0], [3, 2, 1], [4, -1, 2]] - Justification:
- Starting from the gates, calculate the minimum distance for each empty room. Each room contains the minimum steps to the nearest gate.
Example 2
- Input:
[[0, 2147483647, 2147483647, 0], [2147483647, -1, 2147483647, 2147483647], [2147483647, -1, -1, 2147483647], [0, 2147483647, 2147483647, 0]] - Expected Output:
[[0, 1, 1, 0], [1, -1, 2, 1], [1, -1, -1, 1], [0, 1, 1, 0]] - Justification:
- The gates at the corners spread their distances to the empty rooms.
Example 3
- Input:
[[2147483647, -1, 0, 2147483647], [-1, 2147483647, 2147483647, -1], [0, -1, 2147483647, 2147483647], [2147483647, -1, 2147483647, -1]] - Expected Output:
[[2147483647, -1, 0, 1], [-1, 2, 1, -1], [0, -1, 2, 3], [1, -1, 3, -1]] - Justification:
- The gates in the middle of the grid spread their distances, and the walls prevent certain paths.
Constraints:
- m == rooms.length
- n == rooms[i].length
- 1 <= m, n <= 250
- rooms[i][j] is -1, 0, or 231 - 1.
Try it yourself
Try solving this question here:
✅ Solution Walls and Gates
Problem Statement
You are given a grid of size m x n filled with three possible values:
-1representing a wall or an obstacle.0representing a gate.2147483647(INF) representing an empty room.
Fill each empty room with the distance to its nearest gate. If an empty room cannot reach any gate, it should remain 2147483647.
Examples
Example 1
- Input:
[[2147483647, -1, 0], [2147483647, 2147483647, 2147483647], [2147483647, -1, 2147483647]] - Expected Output:
[[4, -1, 0], [3, 2, 1], [4, -1, 2]] - Justification:
- Starting from the gates, calculate the minimum distance for each empty room. Each room contains the minimum steps to the nearest gate.
Example 2
- Input:
[[0, 2147483647, 2147483647, 0], [2147483647, -1, 2147483647, 2147483647], [2147483647, -1, -1, 2147483647], [0, 2147483647, 2147483647, 0]] - Expected Output:
[[0, 1, 1, 0], [1, -1, 2, 1], [1, -1, -1, 1], [0, 1, 1, 0]] - Justification:
- The gates at the corners spread their distances to the empty rooms.
Example 3
- Input:
[[2147483647, -1, 0, 2147483647], [-1, 2147483647, 2147483647, -1], [0, -1, 2147483647, 2147483647], [2147483647, -1, 2147483647, -1]] - Expected Output:
[[2147483647, -1, 0, 1], [-1, 2, 1, -1], [0, -1, 2, 3], [1, -1, 3, -1]] - Justification:
- The gates in the middle of the grid spread their distances, and the walls prevent certain paths.
Constraints:
- m == rooms.length
- n == rooms[i].length
- 1 <= m, n <= 250
- rooms[i][j] is -1, 0, or 231 - 1.
Solution
To solve this problem, we need to use a breadth-first search (BFS) approach starting from each gate (0) and moving outward to calculate the shortest distance to each empty room (2147483647). BFS is suitable here because it explores all possible steps from the source nodes (gates) level by level, ensuring that we find the shortest path to each room.
The BFS approach ensures that we fill each empty room with the minimum distance to any gate. By processing all gates simultaneously, we guarantee that we correctly handle the distances even when multiple gates influence the same empty room.
Step-by-step Algorithm
-
Initialize a Queue:
- Create an empty queue to store the coordinates of the gates.
-
Add Gates to Queue:
- Traverse the grid.
- For each cell, if it contains a gate (value 0), add its coordinates to the queue.
-
Breadth-First Search (BFS) Initialization:
- Define the directions array to explore the four possible moves (up, down, left, right).
-
BFS Execution:
- While the queue is not empty:
- Dequeue a cell from the queue.
- For each direction in the directions array:
- Calculate the new cell coordinates by adding the direction values to the current cell coordinates.
- Check if the new cell is within the grid boundaries and if it is an empty room (value
2147483647). - If valid, update the new cell's value to the current cell's value + 1.
- Enqueue the new cell's coordinates.
- While the queue is not empty:
-
End:
- Continue until the queue is empty, meaning all reachable cells have been processed.
Algorithm Walkthrough
Input:
[[2147483647, -1, 0],
[2147483647, 2147483647, 2147483647],
[2147483647, -1, 2147483647]]
-
Initialization:
- Queue:
[] - Directions:
[(-1, 0), (0, 1), (1, 0), (0, -1)]
- Queue:
-
Add Gates to Queue:
- Traverse the grid and find the gate at
(0, 2). - Add
(0, 2)to the queue. - Queue:
[(0, 2)]
- Traverse the grid and find the gate at
-
BFS Execution:
-
First Level (Distance 0):
- Dequeue
(0, 2), process it. - Explore directions:
- Up:
(-1, 2)(out of bounds) - Right:
(0, 3)(out of bounds) - Down:
(1, 2)- Update value at
(1, 2)to1. - Enqueue
(1, 2).
- Update value at
- Left:
(0, 1)(wall)
- Up:
- Grid:
[[2147483647, -1, 0], [2147483647, 2147483647, 1], [2147483647, -1, 2147483647]] - Queue:
[(1, 2)]
- Dequeue
-
Second Level (Distance 1):
- Dequeue
(1, 2), process it. - Explore directions:
- Up:
(0, 2)(gate, already processed) - Right:
(1, 3)(out of bounds) - Down:
(2, 2)- Update value at
(2, 2)to2. - Enqueue
(2, 2).
- Update value at
- Left:
(1, 1)- Update value at
(1, 1)to2. - Enqueue
(1, 1).
- Update value at
- Up:
- Grid:
[[2147483647, -1, 0], [2147483647, 2, 1], [2147483647, -1, 2]] - Queue:
[(2, 2), (1, 1)]
- Dequeue
-
Third Level (Distance 2):
- Dequeue
(2, 2), process it. - Explore directions:
- Up:
(1, 2)(already processed) - Right:
(2, 3)(out of bounds) - Down:
(3, 2)(out of bounds) - Left:
(2, 1)(wall)
- Up:
- Dequeue
(1, 1), process it. - Explore directions:
- Up:
(0, 1)(wall) - Right:
(1, 2)(already processed) - Down:
(2, 1)(wall) - Left:
(1, 0)- Update value at
(1, 0)to3. - Enqueue
(1, 0).
- Update value at
- Up:
- Grid:
[[2147483647, -1, 0], [3, 2, 1], [2147483647, -1, 2]] - Queue:
[(1, 0)]
- Dequeue
-
Fourth Level (Distance 3):
- Dequeue
(1, 0), process it. - Explore directions:
- Up:
(0, 0)- Update value at
(0, 0)to4. - Enqueue
(0, 0).
- Update value at
- Right:
(1, 1)(already processed) - Down:
(2, 0)- Update value at
(2, 0)to4. - Enqueue
(2, 0).
- Update value at
- Left:
(1, -1)(out of bounds)
- Up:
- Grid:
[[4, -1, 0], [3, 2, 1], [4, -1, 2]] - Queue:
[(0, 0), (2, 0)]
- Dequeue
-
Fifth Level (Distance 4):
- Dequeue
(0, 0), process it. - Explore directions:
- Up:
(-1, 0)(out of bounds) - Right:
(0, 1)(wall) - Down:
(1, 0)(already processed) - Left:
(0, -1)(out of bounds)
- Up:
- Dequeue
(2, 0), process it. - Explore directions:
- Up:
(1, 0)(already processed) - Right:
(2, 1)(wall) - Down:
(3, 0)(out of bounds) - Left:
(2, -1)(out of bounds)
- Up:
- Grid:
[[4, -1, 0], [3, 2, 1], [4, -1, 2]] - Queue:
[]
- Dequeue
-
-
End:
- The queue is empty, the process is complete.
- Final Grid:
[[4, -1, 0], [3, 2, 1], [4, -1, 2]]
Code
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
private static final int INF = 2147483647;
private static final int[] DIRS = { -1, 0, 1, 0, -1 };
public int[][] wallsAndGates(int[][] rooms) {
int m = rooms.length, n = rooms[0].length;
Queue<int[]> queue = new LinkedList<>();
// Add all gates to the queue
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (rooms[i][j] == 0) {
queue.offer(new int[] { i, j });
}
}
}
// Perform BFS from each gate
while (!queue.isEmpty()) {
int[] point = queue.poll();
int x = point[0], y = point[1];
for (int k = 0; k < 4; k++) {
int nx = x + DIRS[k], ny = y + DIRS[k + 1];
// Check if the new position is valid and is an empty room
if (
nx < 0 || nx >= m || ny < 0 || ny >= n || rooms[nx][ny] != INF
) continue;
rooms[nx][ny] = rooms[x][y] + 1;
queue.offer(new int[] { nx, ny });
}
}
return rooms;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] example1 = {
{ 2147483647, -1, 0 },
{ 2147483647, 2147483647, 2147483647 },
{ 2147483647, -1, 2147483647 },
};
sol.wallsAndGates(example1);
printGrid(example1);
int[][] example2 = {
{ 0, 2147483647, 2147483647, 0 },
{ 2147483647, -1, 2147483647, 2147483647 },
{ 2147483647, -1, -1, 2147483647 },
{ 0, 2147483647, 2147483647, 0 },
};
sol.wallsAndGates(example2);
printGrid(example2);
int[][] example3 = {
{ 2147483647, -1, 0, 2147483647 },
{ -1, 2147483647, 2147483647, -1 },
{ 0, -1, 2147483647, 2147483647 },
{ 2147483647, -1, 2147483647, -1 },
};
sol.wallsAndGates(example3);
printGrid(example3);
}
// Helper method to print the grid
private static void printGrid(int[][] grid) {
for (int[] row : grid) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
}
Complexity Analysis
Time Complexity:
The time complexity of the algorithm is
Space Complexity:
The space complexity is also
🤖 Don't fully get this? Learn it with Claude
Stuck on Walls and Gates? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Walls and Gates** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Walls and Gates** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Walls and Gates**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Walls and Gates**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.