-
Notifications
You must be signed in to change notification settings - Fork 7
/
542-01-Matrix.js
43 lines (38 loc) · 1.1 KB
/
542-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
// 542. 01 Matrix [Medium]
// https://leetcode.com/problems/01-matrix/
/**
* @param {number[][]} mat
* @return {number[][]}
*/
const updateMatrix = (mat) => {
const m = mat.length;
const n = mat[0].length;
const dp = new Array(m).fill(null).map(() => new Array(n).fill(Infinity));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] === 0) {
dp[i][j] = 0;
} else {
if (i > 0) {
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1);
}
if (j > 0) {
dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1);
}
}
}
}
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (mat[i][j] !== 0) {
if (i < m - 1) {
dp[i][j] = Math.min(dp[i][j], dp[i + 1][j] + 1);
}
if (j < n - 1) {
dp[i][j] = Math.min(dp[i][j], dp[i][j + 1] + 1);
}
}
}
}
return dp;
};