-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
60 lines (51 loc) · 1.24 KB
/
index.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
52
53
54
55
56
57
58
59
/**
* Problem: https://leetcode.com/problems/01-matrix/description/
*/
/**
* @param {number[][]} matrix
* @return {number[][]}
*/
var updateMatrix = function (matrix) {
var result = [], nodes = [], init = 1;
var collectNodes = function ([x, y]) {
if (matrix[x - 1] && matrix[x - 1][y]) {
if (result[x - 1][y] === undefined) {
result[x - 1][y] = init;
nodes.push([x - 1, y]);
}
}
if (matrix[x][y - 1]) {
if (result[x][y - 1] === undefined) {
result[x][y - 1] = init;
nodes.push([x, y - 1]);
}
}
if (matrix[x + 1] && matrix[x + 1][y]) {
if (result[x + 1][y] === undefined) {
result[x + 1][y] = init;
nodes.push([x + 1, y]);
}
}
if (matrix[x][y + 1]) {
if (result[x][y + 1] === undefined) {
result[x][y + 1] = init;
nodes.push([x, y + 1]);
}
}
};
for (var i = 0; i < matrix.length; ++i) result.push([]);
matrix.forEach(function (row, i) {
row.forEach(function (col, j) {
if (!col) {
result[i][j] = 0;
collectNodes([i, j]);
}
});
});
while (nodes.length) {
++init;
var temp = [].concat(nodes), nodes = [];
temp.forEach(collectNodes);
}
return result;
};