-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
51 lines (50 loc) · 1.34 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @param {number[][]} matrix
* @return {number[][]}
*/
// BFS
var updateMatrix = function (matrix) {
const queue = [];
const result = [];
const row = matrix.length;
const column = matrix[0].length;
for (let i = 0; i < row; i++) {
const rowArr = new Array(column);
for (let j = 0; j < column; j++) {
if (matrix[i][j] === 0) {
rowArr[j] = 0;
queue.push([
i, j, ]);
} else {
rowArr[j] = Infinity;
}
}
result[i] = rowArr;
}
while (queue.length) {
const [
x, y, ] = queue.shift();
const newDis = result[x][y] + 1;
if (x > 0 && newDis < result[x - 1][y]) {
result[x - 1][y] = newDis;
queue.push([
x - 1, y, ]);
}
if (y < column - 1 && newDis < result[x][y + 1]) {
result[x][y + 1] = newDis;
queue.push([
x, y + 1, ]);
}
if (x < row - 1 && newDis < result[x + 1][y]) {
result[x + 1][y] = newDis;
queue.push([
x + 1, y, ]);
}
if (y > 0 && newDis < result[x][y - 1]) {
result[x][y - 1] = newDis;
queue.push([
x, y - 1, ]);
}
}
return result;
};