Walls and Gates

Question (LC.286)

Given a 2D grid map, where -1 represents a wall, 0 represents a gate, and INF represents an empty room, fill each empty room with the distance to its nearest gate.

If it is impossible for an empty room to reach a gate, it should be filled with INF.

Example

I:
INF  -1  0  INF
INF INF INF  -1
INF  -1 INF  -1
  0  -1 INF INF
O:
3  -1   0   1
2   2   1  -1
1  -1   2  -1
0  -1   3   4

From Src to Dst

for the entire graph
    if the room is empty
        BFS(room) to find the nearest gate

Code

public void wallsAndGates(int[][] rooms) {
    int m = rooms.length;
    int n = rooms[0].length;        
    // search entire graph
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (rooms[i][j] != INF) {
                continue;
            }
            int distance = bfsGate(rooms, new Pos(i,j));
            if (distance > 0) {
                rooms[i][j] = distance;
            }
        }
    }
}

private int bfsGate(int[][] rooms, Pos start) {
    // init queue
    Queue<Pos> queue = new LinkedList<>();
    boolean visited[][] = new boolean[rooms.length][rooms[0].length];
    queue.offer(start);
    visited[start.row][start.col] = true;
    // bfs by layer
    int layers = 0;
    Pos current;
    // stop when searched the connected component or found the gate
    while (!queue.isEmpty()) {
        // search by level
        int queueSize = queue.size();
        for (int i = 0; i < queueSize; i++) {
            current = queue.poll();
            for (int p = 0; p < 4; p++) {
                Pos neighbor = new Pos(current.row + drow[p], current.col + dcol[p]);
                if (!inBound(rooms, neighbor)) continue;
                if (visited[neighbor.row][neighbor.col]) continue;
                int roomType = rooms[neighbor.row][neighbor.col];
                if (roomType == -1) continue; // wall
                if (roomType == 0) return layers + 1; // gate
                queue.offer(neighbor); // empty
                visited[neighbor.row][neighbor.col] = true;
            }
        }
        layers++;            
    }
    return 0; // didn't find a gate
}

The last test case on LC gives this code a TLE. Let N = #nodes. The worst case time complexity is O(N). DFS doesn't help in this case. We are stuck with BFS. How can we do better?

From Dst to Src

We can reverse the starting points. If we start searching from the gates and update the empty rooms we can vastly improve the time complexity. Specifically, O(#gates * N) = O(N).

Step 1 Put all gates to queue
Step 2 BFS update empty rooms when the first one gets there
       if an empty room is unreachable, it keeps INF

Notice that we don't need visited since we only put unprocessed empty rooms into the queue.

Code

static final int WALL = -1, INF = Integer.MAX_VALUE, GATE = 0;

public void wallsAndGates(int[][] rooms) {    
    int m = rooms.length;
    int n = rooms[0].length;
    // Step 1 init queue with dst
    Queue<Pos> queue = new LinkedList<>();
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (rooms[i][j] == GATE) {
                queue.offer(new Pos(i,j));
            }
        }
    }
    // Step 2 level BFS to reach src
    Pos current;
    int levels = 0;
    while (!queue.isEmpty()) {
        int queueSize = queue.size();
        for (int i = 0; i < queueSize; i++) { // no need for this but keep it anyway
            current = queue.poll();
            // search neighbors
            for (int p = 0; p < 4; p++) {
                Pos neighbor = new Pos(current.row + drow[p], current.col + dcol[p]);
                if (!inBound(rooms, neighbor)) continue;
                if (rooms[neighbor.row][neighbor.col] == INF) {
                    rooms[neighbor.row][neighbor.col] = levels + 1;
                    queue.offer(neighbor);
                }
            }

        }
        levels++;
    }
}

The question cleverly gives gate the value 0. We can tabulate the distance across the table so we don't really need the for loop that keeps tracks of the levels. We can use the current level rooms[neighbor.row][neighbor.col] = rooms[current.row][current.col] + 1 instead of a level variable.

Last updated