1. BFS from Every Empty Room
Intuition
Search outward from each room until hitting a cell with value 0.
Algorithm
- Step 1: Iterate through every cell (r, c) in the grid.
- Step 2: If rooms[r][c] == 2147483647, launch helper bfs(r, c).
- Step 3: Inside BFS, maintain queue and visited set.
- Step 4: Pop (currR, currC, dist); if rooms[currR][currC] == 0, record dist and terminate BFS.
- Step 5: Overwrite rooms[r][c] with the minimum distance found.
BFS from Every Empty Room Trace
2 of 2 questions left todayIterate grid cells
Iterate grid cells. Find empty room at (0,0) (val INF). Launch independent BFS.
#include <iostream>#include <vector>#include <queue>#include <tuple> class Solution { const int INF = 2147483647; int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};public: void wallsAndGates(std::vector<std::vector<int>>& rooms) { if (rooms.empty() || rooms[0].empty()) return; int m = rooms.size(), n = rooms[0].size(); for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { if (rooms[r][c] == INF) { std::queue<std::tuple<int, int, int>> q; std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false)); q.push({r, c, 0}); visited[r][c] = true; int minDist = INF; while (!q.empty()) { auto [cr, cc, d] = q.front(); q.pop(); if (rooms[cr][cc] == 0) { minDist = d; break; } for (auto& dir : dirs) { int nr = cr + dir[0], nc = cc + dir[1]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && rooms[nr][nc] != -1 && !visited[nr][nc]) { visited[nr][nc] = true; q.push({nr, nc, d + 1}); } } } rooms[r][c] = minDist; } } } }}; int main() { Solution solver; const int INF = 2147483647; std::vector<std::vector<int>> rooms = { {INF, -1, 0, INF}, {INF, INF, INF, -1}, {INF, -1, INF, -1}, {0, -1, INF, INF} }; solver.wallsAndGates(rooms); for (const auto& row : rooms) { for (int x : row) std::cout << x << " "; std::cout << ""; } return 0;}Time & Space Complexity
- Time complexity:
O((M * N)^2)— Time complexity for BFS from Every Empty Room. - Space complexity:
O(M * N)— Space complexity for BFS from Every Empty Room.
Why Brute Force Doesn't Scale:
With 250x250 cells (62,500 cells), single-room BFS performs up to 62,500 * 62,500 = 3.9 * 109 operations.
Multi-Source BFS does at most 62,500 queue pops, executing in ~15 milliseconds.