Skip to content

Commit 68bbf67

Browse files
authored
Create 1162-as-far-from-land-as-possible.js
1 parent 1637f03 commit 68bbf67

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

1162-as-far-from-land-as-possible.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const maxDistance = function(grid) {
6+
let m = grid.length
7+
let n = m === 0 ? 0 : grid[0].length
8+
let dp = new Array(m + 2)
9+
for (let i = 0; i < m + 2; i++) {
10+
dp[i] = new Array(n + 2).fill(Number.POSITIVE_INFINITY)
11+
}
12+
for (let i = 1; i <= m; i++) {
13+
for (let j = 1; j <= n; j++) {
14+
if (grid[i - 1][j - 1] === 0) {
15+
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1
16+
} else {
17+
dp[i][j] = 0
18+
}
19+
}
20+
}
21+
let res = Number.NEGATIVE_INFINITY
22+
for (let i = m; i >= 1; i--) {
23+
for (let j = n; j >= 1; j--) {
24+
if (grid[i - 1][j - 1] === 0) {
25+
dp[i][j] = Math.min(dp[i][j], Math.min(dp[i + 1][j], dp[i][j + 1]) + 1)
26+
res = Math.max(res, dp[i][j])
27+
}
28+
}
29+
}
30+
return isFinite(res) ? res : -1
31+
}

0 commit comments

Comments
 (0)