01 Matrix LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} mat
3
* @return {number[][]}
4
*/
5
var updateMatrix = function (mat) {
6
const rows = mat.length,
7
cols = mat[0].length;
8

9
if (!rows) return mat;
10

11
const queue = new Queue();
12
const dist = Array.from({ length: rows }, () =>
13
new Array(cols).fill(Infinity)
14
);
15

16
for (let i = 0; i < rows; i++) {
17
for (let j = 0; j < cols; j++) {
18
if (!mat[i][j]) {
19
dist[i][j] = 0;
20
queue.enqueue([i, j]);
21
}
22
}
23
}
24

25
const dirs = [
26
[-1, 0],
27
[1, 0],
28
[0, -1],
29
[0, 1],
30
];
31

32
while (!queue.isEmpty()) {
33
const [row, col] = queue.dequeue();
34
for (let i = 0; i < 4; i++) {
35
const nRow = row + dirs[i][0],
36
nCol = col + dirs[i][1];
37

38
if (nRow < 0 || nCol < 0 || nRow >= rows || nCol >= cols) continue;
39

40
if (dist[nRow][nCol] > dist[row][col] + 1) {
41
dist[nRow][nCol] = dist[row][col] + 1;
42
queue.enqueue([nRow, nCol]);
43
}
44
}
45
}
46

47
return dist;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0