Skip to content

Commit 8dbc353

Browse files
authored
Create 542-01-matrix.js
1 parent 9c226b7 commit 8dbc353

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

542-01-matrix.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[][]}
4+
*/
5+
6+
const updateMatrix = function (matrix) {
7+
const rows = matrix.length, cols = matrix[0].length;
8+
const maxDist = rows + cols;
9+
let dist = new Array(rows).fill(null).map(() => new Array(cols).fill(0));
10+
11+
for (let i = 0; i < rows; i++) {
12+
for (let j = 0; j < cols; j++) {
13+
if (matrix[i][j] !== 0) {
14+
dist[i][j] = hasNeighborZero(i, j, matrix, rows, cols) ? 1 : maxDist;
15+
}
16+
}
17+
}
18+
19+
for (let i = 0; i < rows; i++) {
20+
for (let j = 0; j < cols; j++) {
21+
if (dist[i][j] === 1) {
22+
dfs(dist, i, j, -1);
23+
}
24+
}
25+
}
26+
27+
return dist;
28+
};
29+
30+
const dfs = function (dist, row, col, step) {
31+
if (row < 0 || row >= dist.length || col < 0 || col >= dist[0].length || dist[row][col] <= step) return;
32+
33+
if (step > 0) dist[row][col] = step;
34+
35+
dfs(dist, row + 1, col, dist[row][col] + 1);
36+
dfs(dist, row - 1, col, dist[row][col] + 1);
37+
dfs(dist, row, col + 1, dist[row][col] + 1);
38+
dfs(dist, row, col - 1, dist[row][col] + 1);
39+
};
40+
41+
const hasNeighborZero = function (row, col, matrix, rows, cols) {
42+
if (row < rows - 1 && matrix[row + 1][col] === 0) return true;
43+
if (row > 0 && matrix[row - 1][col] === 0) return true;
44+
if (col > 0 && matrix[row][col - 1] === 0) return true;
45+
if (col < cols - 1 && matrix[row][col + 1] === 0) return true;
46+
47+
return false;
48+
};

0 commit comments

Comments
 (0)