Algo-Sim › Grid Graphs

Walls and Gates

Medium · Grid Graphs · step through it in Java, Python and C++ on your own input

Fill each empty room with its distance to the nearest gate (walls are -1, gates 0, unreachable rooms keep INF).

Problem

A grid has walls (-1), gates (0) and empty rooms (INF). Fill every empty room with the number of steps to its nearest gate, moving up, down, left or right. Rooms that cannot reach a gate stay INF.

Constraints

Edge cases to test

Follow-up questions

Why start from the gates?
BFS from all gates at once fills each room with its nearest distance in O(mn); starting from rooms is O((mn)²).
How does it relate to 01 Matrix?
It is the same multi-source BFS, with walls blocking the way.

Solution

Java

public void wallsAndGates(int[][] rooms) {
    int rows = rooms.length, cols = rooms[0].length;
    int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
    Queue<int[]> queue = new ArrayDeque<>();
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (rooms[r][c] == 0) queue.offer(new int[] { r, c });
        }
    }
    while (!queue.isEmpty()) {
        int[] cell = queue.poll();
        for (int[] d : dirs) {
            int nr = cell[0] + d[0], nc = cell[1] + d[1];
            if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || rooms[nr][nc] != Integer.MAX_VALUE) continue;
            rooms[nr][nc] = rooms[cell[0]][cell[1]] + 1;
            queue.offer(new int[] { nr, nc });
        }
    }
}

Python

from collections import deque

INF = 2147483647

def walls_and_gates(rooms):
    rows, cols = len(rooms), len(rooms[0])
    dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    queue = deque()
    for r in range(rows):
        for c in range(cols):
            if rooms[r][c] == 0:
                queue.append((r, c))
    while queue:
        cr, cc = queue.popleft()
        for dr, dc in dirs:
            nr, nc = cr + dr, cc + dc
            if not (0 <= nr < rows and 0 <= nc < cols) or rooms[nr][nc] != INF:
                continue
            rooms[nr][nc] = rooms[cr][cc] + 1
            queue.append((nr, nc))

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void wallsAndGates(vector<vector<int>> &rooms) {
        int rows = int(rooms.size()), cols = int(rooms[0].size());
        vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        deque<vector<int>> queue = {};
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (rooms[r][c] == 0)
                    queue.push_back(vector<int>{r, c});
            }
        }
        while (!queue.empty()) {
            vector<int> cell = queue.front();
            queue.pop_front();
            for (vector<int> &d : dirs) {
                int nr = cell[0] + d[0], nc = cell[1] + d[1];
                if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || rooms[nr][nc] != INT_MAX)
                    continue;
                rooms[nr][nc] = rooms[cell[0]][cell[1]] + 1;
                queue.push_back(vector<int>{nr, nc});
            }
        }
    }
};

More Grid Graphs problems