Skip to content

Commit c8c16d7

Browse files
authored
Update 1631-path-with-minimum-effort.js
1 parent acd86bb commit c8c16d7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

1631-path-with-minimum-effort.js

+44
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
1+
/**
2+
* @param {number[][]} heights
3+
* @return {number}
4+
*/
5+
const minimumEffortPath = function(heights) {
6+
const m = heights.length, n = heights[0].length
7+
const { abs, floor } = Math
8+
let l = 0, r= 1e6
9+
10+
while(l < r) {
11+
const mid = l + floor((r- l) /2)
12+
if(valid(mid)) {
13+
r = mid
14+
} else {
15+
l = mid + 1
16+
}
17+
}
18+
19+
return l
20+
21+
function valid(effort) {
22+
const visited = Array.from({length:m}, () => Array(n).fill(0))
23+
const dirs = [[1,0],[-1,0],[0,1],[0,-1]]
24+
let q = []
25+
q.push([0, 0])
26+
visited[0][0] = 1
27+
while(q.length) {
28+
const [x, y] = q.shift()
29+
for(const [dx, dy] of dirs) {
30+
const nx = x + dx, ny = y + dy
31+
if(nx<0 || nx>=m || ny < 0 || ny >= n) continue
32+
if(visited[nx][ny]) continue
33+
if(abs(heights[nx][ny] - heights[x][y]) > effort) continue
34+
q.push([nx,ny])
35+
visited[nx][ny] = 1
36+
}
37+
}
38+
39+
return visited[m - 1][n - 1] === 1
40+
}
41+
};
42+
43+
// another
44+
145
/**
246
* @param {number[][]} heights
347
* @return {number}

0 commit comments

Comments
 (0)