286. Walls and Gates
202408211447
tags: #bfs
var wallsAndGates = function(rooms) {
const INF = 2147483647;
const m = rooms.length;
const n = rooms[0].length;
const DIRS = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const q = [];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (rooms[i][j] === 0) {
q.push([i, j]);
}
}
}
while (q.length > 0) {
const [i, j] = q.shift();
for (const [dx, dy] of DIRS) {
const x = i + dx;
const y = j + dy
if (x < 0 || y 0 || x >= m || y >= n || rooms[x][y] !== INF) {
continue;
}
rooms[x][y] = rooms[i][j] + 1;
q.push([x, y]);
}
}
};