</>

286. Walls and Gates

Medium NeetCode 150
Graphs Time O(m*n) Space O(m*n)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Graphs
Time
O(m*n)
Space
O(m*n)

Standard Solution (C++)

SummaryIn a grid of gates, walls, and empty rooms, fill each empty room with its distance to the nearest gate, leaving rooms unreachable from any gate untouched.

Approach

Multi-source BFS from all gates at once.

  • Seed a queue with every gate cell (value 0).
  • Expand outward in lockstep; the first time a room is reached gives its shortest gate distance.
  • Walls (value -1) and already-filled rooms are skipped, so each cell is processed once.
class Solution {
public:
    void wallsAndGates(vector<vector<int>>& rooms) {
        const int INF = 2147483647;
        int m = rooms.size();
        if (m == 0) return;
        int n = rooms[0].size();
        queue<pair<int,int>> q;
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                if (rooms[i][j] == 0) q.push({i, j});
        int dirs[5] = {-1, 0, 1, 0, -1};
        while (!q.empty()) {
            auto [r, c] = q.front(); q.pop();
            for (int d = 0; d < 4; ++d) {
                int nr = r + dirs[d], nc = c + dirs[d+1];
                if (nr < 0 || nc < 0 || nr >= m || nc >= n) continue;
                if (rooms[nr][nc] != INF) continue;
                rooms[nr][nc] = rooms[r][c] + 1;
                q.push({nr, nc});
            }
        }
    }
};
Time O(m*n) Space O(m*n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern