Walls and Gates
Write into each empty room of a grid how many steps it is from the nearest gate.
A floor plan is drawn as a grid rooms
: a wall;-1 : a gate;0 (2147483647): an empty room.INF
Fill each empty room with the number of steps to its nearest gate, where one step moves to the square above, below, left or right, and never into a wall. A room that cannot reach any gate stays INF
Example 1
Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
The Idea
Think of the grid as one floor of a building seen from above. Some squares are walls, some are doors to the outside, called gates, and the rest are rooms. For every room we want a sign that says how many steps it takes to walk out through the closest gate.
Look at the picture below. On the left, under "rooms before", is Example 1, and on the right, under "rooms after", the same grid filled in. The two orange squares, labelled "gate" in the key, are the gates, at row 0, column 2 and at row 3, column 0.
The room at row 0, column 3 sits right next to the top gate, so it gets 1. The room at row 1, column 1 is 2 steps from the top gate and 3 steps from the bottom one, so it gets the smaller number, 2. The room at row 3, column 3 has to walk around the walls: left, up, up and up again, 4 steps.
Each room's number depends on every gate and every wall in the way. Must we really walk out from each room on its own, again and again, until it finds a gate?
Turn the question around and walk out from the gates instead. Picture all the gates opening at the same moment and water spreading from each, one square per tick, around the walls. After one tick the squares beside a gate are wet, and they get 1. After two ticks the next ring is wet, and those squares get 2.
Water from the closest gate always arrives first, so the tick at which a room first gets wet is exactly its distance. In the picture, the blue rooms, labelled "nearest gate: row 0, column 2", got wet first from that gate, and the teal rooms, labelled "nearest gate: row 3, column 0", from the other one.
Seen this way, the grid is a graph: each open square is a point, and two open squares side by side are joined. Visiting every square one step away, then every square two steps away, and so on, is called breadth-first search (BFS). Starting it from all the gates at once is called a multi-source BFS.
Solution Approach
Turning the spreading water into code means settling four things: why to start at the gates, how to keep squares in tick order, how to spot rooms already reached, and why all gates start together.
Searching from every room
What would the direct way cost? A separate search from each room, stopping at the first gate, may cross most of the grid every time. With m × n squares that is up to (m × n)2 steps, and most of them repeat work an earlier search already did. Starting at the gates covers each square once.
Keeping squares in tick order
How do we make sure every square at distance 1 is handled before any square at distance 2? Put squares in a queue, a line where the first square added is the first taken out. The gates go in first. Each square taken out wets its open neighbours and adds them to the back of the line.
A square at distance d only ever adds squares at distance d + 1, behind everything already waiting. So the line always holds squares of at most two neighbouring distances, the smaller ones in front. The code keeps this line in an ArrayDequeaddpoll
A graph search often starts by building an adjacency list, a list of neighbours for every point. The grid needs none: the neighbours of a square are simply the four squares above, below, left and right of it, one row or one column away.
Telling which rooms are reached
How do we avoid wetting a room twice? The value INFINFINF
Why the gates start together
Could we search from one gate, then from the next, with the same INF
Look at row 2, column 0: it got 4, although it sits right next to the bottom gate. When the bottom gate's turn came, its only open neighbour already held 4, so its search ended at once. With every gate in the queue from the start, the closest gate's water always gets to a room first.
Java Solution
The method wallsAndGates
- First, read the grid's size into
(rows) andm (columns), and createn , anqueue of squares, each stored asArrayDeque . Visit every square with two loops, one inside the other, and add each gate (value 0) to{row, column} .queue - Write the four possible moves into
: down, up, right and left, each as a change of row and column.dirs - While
is not empty, take the front square,queue , withcell . For each move inqueue.poll() , work out the neighbour's rowdirs and columnr .c - If the neighbour lies inside the grid and still holds
, writeINF 's distance plus 1 into it and add it to the back ofcell .queue - When
is empty, every room a gate can reach holds its distance, and the rest still holdqueue . The method returns nothing, because it changesINF in place.rooms
The main
import java.util.ArrayDeque;
import java.util.Deque;
public class WallsAndGates {
private static final int INF = Integer.MAX_VALUE;
public static void wallsAndGates(int[][] rooms) {
int m = rooms.length, n = rooms[0].length;
Deque<int[]> queue = new ArrayDeque<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (rooms[r][c] == 0) {
queue.add(new int[] {r, c}); // every gate starts at distance 0
}
}
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
for (int[] d : dirs) {
int r = cell[0] + d[0], c = cell[1] + d[1];
// only rooms not reached yet: walls and gates never hold INF
if (r >= 0 && r < m && c >= 0 && c < n && rooms[r][c] == INF) {
rooms[r][c] = rooms[cell[0]][cell[1]] + 1;
queue.add(new int[] {r, c});
}
}
}
}
static void run(String name, int[][] rooms) {
wallsAndGates(rooms);
System.out.println(name + ":");
for (int[] row : rooms) {
StringBuilder sb = new StringBuilder();
for (int v : row) {
sb.append(String.format("%4s", v == INF ? "INF" : String.valueOf(v)));
}
System.out.println(sb);
}
}
public static void main(String[] args) {
run("Example 1", new int[][] {
{INF, -1, 0, INF},
{INF, INF, INF, -1},
{INF, -1, INF, -1},
{0, -1, INF, INF}});
run("No gate", new int[][] {
{INF, -1},
{INF, INF}});
run("Room cut off by walls", new int[][] {
{0, INF, -1, INF},
{INF, INF, -1, INF}});
run("Only a gate", new int[][] {{0}});
}
}
Running it prints:
Example 1:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
No gate:
INF -1
INF INF
Room cut off by walls:
0 1 -1 INF
1 2 -1 INF
Only a gate:
0
The Example 1 grid matches the expected output and the right-hand grid in the picture. Its last row, 0 -1 3 4
With no gate, queueINFINF
Complexity
The work is one scan for gates plus one search in which every square enters the queue at most once.
- Time: O(m × n), because each room is written and queued at most once, since it stops holding
, and each square taken from the queue checks only four neighbours.INF - Space: O(m × n), because the queue can hold a large share of the squares at once, for example when the grid starts full of gates, while the distances go into
itself.rooms
Another search that spreads from many starting squares at once is