-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-matrix.js
44 lines (40 loc) · 1.22 KB
/
01-matrix.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
/**
* @param {number[][]} mat
* @return {number[][]}
*/
var updateMatrix = function(mat) {
let m = mat.length; // row length
let n = mat[0].length; // column length
queue = [] // storing 0 value index
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] == 0) {
queue.push([i, j]);
}
else {
mat[i][j] = Number.MAX_SAFE_INTEGER;
}
}
}
dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
let level = 0;
while (queue.length > 0) {
// rowColIndex[0] --> row index
// rowColIndex[1] --> col index
level++;
let size = queue.length;
for (let i = 0; i < size; i++) {
rowColIndex = queue.shift();
for (let j = 0; j < dirs.length; j++) {
let row = rowColIndex[0] + dirs[j][0];
let col = rowColIndex[1] + dirs[j][1];
if (row < 0 || row >= m || col < 0 || col >= n || mat[row][col] != Number.MAX_SAFE_INTEGER){
continue;
}
queue.push([row, col]);
mat[row][col] = level;
}
}
}
return mat;
};