Skip to content

Commit f08b7bc

Browse files
authored
Create 1631-path-with-minimum-effort.js
1 parent 4ad5b28 commit f08b7bc

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

1631-path-with-minimum-effort.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @param {number[][]} heights
3+
* @return {number}
4+
*/
5+
const minimumEffortPath = function (heights) {
6+
const d = [0, 1, 0, -1, 0]
7+
let lo = 0,
8+
hi = 10 ** 6 + 1
9+
while (lo < hi) {
10+
let effort = lo + ((hi - lo) >> 1)
11+
if (isPath(heights, effort)) {
12+
hi = effort
13+
} else {
14+
lo = effort + 1
15+
}
16+
}
17+
return lo
18+
function isPath(h, effort) {
19+
const m = h.length,
20+
n = h[0].length
21+
const q = []
22+
q.push([0, 0])
23+
const seen = new Set()
24+
seen.add(0)
25+
while (q.length) {
26+
const cur = q.shift()
27+
const x = cur[0],
28+
y = cur[1]
29+
if (x === m - 1 && y === n - 1) {
30+
return true
31+
}
32+
for (let k = 0; k < 4; k++) {
33+
const r = x + d[k],
34+
c = y + d[k + 1]
35+
if(seen.has(r * n + c)) continue
36+
if (
37+
0 <= r &&
38+
r < m &&
39+
0 <= c &&
40+
c < n &&
41+
effort >= Math.abs(h[r][c] - h[x][y])
42+
) {
43+
seen.add(r * n + c)
44+
q.push([r, c])
45+
}
46+
}
47+
}
48+
return false
49+
}
50+
}

0 commit comments

Comments
 (0)