Overview
Given an m × n binary matrix mat, return a matrix where each cell contains the distance to the nearest 0. Distance is measured in terms of adjacent cells (up, down, left, right).
Constraints
1 <= m, n <= 10,000mat[i][j]is either 0 or 1.- There is at least one 0 in the matrix.
Examples
updateMatrix([[0,0,0],[0,1,0],[0,0,0]]); // => [[0,0,0],[0,1,0],[0,0,0]] updateMatrix([[0,0,0],[0,1,0],[1,1,1]]); // => [[0,0,0],[0,1,0],[1,2,1]]
Solution
Reveal solution
function updateMatrix(mat) {
const m = mat.length, n = mat[0].length;
const dist = Array.from({length: m}, () => new Array(n).fill(Infinity));
const queue = [];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
if (mat[i][j] === 0) { dist[i][j] = 0; queue.push([i, j]); }
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
let idx = 0;
while (idx < queue.length) {
const [r, c] = queue[idx++];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n && dist[nr][nc] > dist[r][c] + 1) {
dist[nr][nc] = dist[r][c] + 1;
queue.push([nr, nc]);
}
}
}
return dist;
}Multi-source BFS from all 0 cells simultaneously.
Resources
zero-one-matrix.js
01 Matrix
mediumcodingAlgorithmsBFS
Overview
Given an m × n binary matrix mat, return a matrix where each cell contains the distance to the nearest 0. Distance is measured in terms of adjacent cells (up, down, left, right).
Constraints
1 <= m, n <= 10,000mat[i][j]is either 0 or 1.- There is at least one 0 in the matrix.
Examples
updateMatrix([[0,0,0],[0,1,0],[0,0,0]]); // => [[0,0,0],[0,1,0],[0,0,0]] updateMatrix([[0,0,0],[0,1,0],[1,1,1]]); // => [[0,0,0],[0,1,0],[1,2,1]]
Solution
Reveal solution
function updateMatrix(mat) {
const m = mat.length, n = mat[0].length;
const dist = Array.from({length: m}, () => new Array(n).fill(Infinity));
const queue = [];
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++)
if (mat[i][j] === 0) { dist[i][j] = 0; queue.push([i, j]); }
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
let idx = 0;
while (idx < queue.length) {
const [r, c] = queue[idx++];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < m && nc >= 0 && nc < n && dist[nr][nc] > dist[r][c] + 1) {
dist[nr][nc] = dist[r][c] + 1;
queue.push([nr, nc]);
}
}
}
return dist;
}Multi-source BFS from all 0 cells simultaneously.
Resources
NameTopicDifficulty
103 of 103 problems