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 of m rows and n columns, and each square holds one of three values:

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. Change the grid in place.

Example 1
Input: rooms = [[INF,-1,0,INF],[INF,INF,INF,-1],[INF,-1,INF,-1],[0,-1,INF,INF]]
Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Solution

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.

Example 1 before and after. Every INF room is replaced by its steps to the nearest gate. Blue rooms are nearest to the gate at row 0, column 2, teal rooms to the gate 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 ArrayDeque, where add puts a square at the back and poll takes one from the front.

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 INF already says it. A room still holding INF has not been reached; once reached, it holds a small distance. Walls hold -1 and gates hold 0, so the same check, "is this square INF?", also keeps the search out of walls and off the gates. No separate grid of visited squares is needed.

Why the gates start together

Could we search from one gate, then from the next, with the same INF check? No: the first gate's water would claim rooms that are nearer to the second gate, and the check never lets the second gate correct them. Running that on Example 1, top gate first, gives [[4,-1,0,1],[3,2,1,-1],[4,-1,2,-1],[0,-1,3,4]].

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 works in these steps:

  1. First, read the grid's size into m (rows) and n (columns), and create queue, an ArrayDeque of squares, each stored as {row, column}. Visit every square with two loops, one inside the other, and add each gate (value 0) to queue.
  2. Write the four possible moves into dirs: down, up, right and left, each as a change of row and column.
  3. While queue is not empty, take the front square, cell, with queue.poll(). For each move in dirs, work out the neighbour's row r and column c.
  4. If the neighbour lies inside the grid and still holds INF, write cell's distance plus 1 into it and add it to the back of queue.
  5. When queue is empty, every room a gate can reach holds its distance, and the rest still hold INF. The method returns nothing, because it changes rooms in place.

The main method runs Example 1, a grid with no gate, a grid where a wall cuts two rooms off from the gate, and a grid that is a single gate. It prints each grid row by row.

Java
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:

Output
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, shows the room at row 3, column 3 with 4, the walk around the walls from the top gate.

With no gate, queue starts empty, the search never runs, and all three rooms keep INF. In the grid with a wall down column 2, the left side fills with 1, 1 and 2, while both rooms in column 3 stay INF, because no step crosses the wall. The single gate stays 0.

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 INF, and each square taken from the queue checks only four neighbours.
  • 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 rooms itself.

Another search that spreads from many starting squares at once is Rotting Oranges.