Given an m × n binary matrix, return a matrix where each cell holds the distance to the nearest 0. Adjacent cells are distance 1 apart.
Start a BFS from every 0 at once. The first time the wave reaches a cell, that distance is its shortest distance to a 0.
1function updateMatrix(mat: number[][]): number[][] {2const m = mat.length, n = mat[0].length, queue: number[][] = [];3const dist = mat.map((row, r) => row.map((v, c) => (v === 0 ? (queue.push([r, c]), 0) : Infinity)));4for (let h = 0; h < queue.length; h++) {5const [r, c] = queue[h];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 && dist[x][y] > dist[r][c] + 1) {8dist[x][y] = dist[r][c] + 1; queue.push([x, y]);9}10}11return dist;12}
| 0 | ∞ | ∞ | ∞ |
| ∞ | ∞ | ∞ | ∞ |
| ∞ | ∞ | 0 | ∞ |
| ∞ | ∞ | ∞ | ∞ |
Every 0 is distance 0. Queue all 2 of them.
Space: play/pause · ←/→: step