Fill each empty room (2147483647) of a grid with the distance to its nearest gate (0). Walls (-1) block movement; unreachable rooms stay 2147483647. Modify rooms in place.
Start a BFS from all gates at once. BFS reaches each room first along a shortest path, so each empty room is written exactly once with its final distance.
1function wallsAndGates(rooms: number[][]): void {2const m = rooms.length, n = rooms[0].length, queue: number[][] = [];3for (let r = 0; r < m; r++) for (let c = 0; c < n; c++) if (rooms[r][c] === 0) queue.push([r, c]);4while (queue.length) {5const [r, c] = queue.shift()!;6for (const [x, y] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]])7if (x >= 0 && y >= 0 && x < m && y < n && rooms[x][y] === 2147483647) {8rooms[x][y] = rooms[r][c] + 1; queue.push([x, y]);9}10}11}
| ∞ | ▇ | 0 | ∞ |
| ∞ | ∞ | ∞ | ▇ |
| ∞ | ▇ | ∞ | ▇ |
| 0 | ▇ | ∞ | ∞ |
Start from all 2 gates.
Space: play/pause · ←/→: step