Skip to content

Commit 2aa5d71

Browse files
authored
Update 1631-path-with-minimum-effort.js
1 parent 0678797 commit 2aa5d71

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

1631-path-with-minimum-effort.js

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,100 @@
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 pq = new PriorityQueue()
8+
const dist = Array.from({ length: m }, () => Array(n).fill(Infinity))
9+
pq.push([0, 0, 0])
10+
dist[0][0] = 0
11+
const dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]]
12+
while(!pq.isEmpty()) {
13+
const [v, i, j] = pq.pop()
14+
if(i === m - 1 && j === n - 1) return v
15+
for(const [dx, dy] of dirs) {
16+
const nx = i + dx, ny = j + dy
17+
if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue
18+
const diff = Math.max(v, Math.abs(heights[nx][ny] - heights[i][j]))
19+
if(dist[nx][ny] > diff) {
20+
dist[nx][ny] = diff
21+
pq.push([diff, nx, ny])
22+
}
23+
}
24+
}
25+
return -1
26+
};
27+
28+
class PriorityQueue {
29+
constructor(comparator = (a, b) => a[0] < b[0]) {
30+
this.heap = []
31+
this.top = 0
32+
this.comparator = comparator
33+
}
34+
size() {
35+
return this.heap.length
36+
}
37+
isEmpty() {
38+
return this.size() === 0
39+
}
40+
peek() {
41+
return this.heap[this.top]
42+
}
43+
push(...values) {
44+
values.forEach((value) => {
45+
this.heap.push(value)
46+
this.siftUp()
47+
})
48+
return this.size()
49+
}
50+
pop() {
51+
const poppedValue = this.peek()
52+
const bottom = this.size() - 1
53+
if (bottom > this.top) {
54+
this.swap(this.top, bottom)
55+
}
56+
this.heap.pop()
57+
this.siftDown()
58+
return poppedValue
59+
}
60+
replace(value) {
61+
const replacedValue = this.peek()
62+
this.heap[this.top] = value
63+
this.siftDown()
64+
return replacedValue
65+
}
66+
67+
parent = (i) => ((i + 1) >>> 1) - 1
68+
left = (i) => (i << 1) + 1
69+
right = (i) => (i + 1) << 1
70+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
71+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
72+
siftUp = () => {
73+
let node = this.size() - 1
74+
while (node > this.top && this.greater(node, this.parent(node))) {
75+
this.swap(node, this.parent(node))
76+
node = this.parent(node)
77+
}
78+
}
79+
siftDown = () => {
80+
let node = this.top
81+
while (
82+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
83+
(this.right(node) < this.size() && this.greater(this.right(node), node))
84+
) {
85+
let maxChild =
86+
this.right(node) < this.size() &&
87+
this.greater(this.right(node), this.left(node))
88+
? this.right(node)
89+
: this.left(node)
90+
this.swap(node, maxChild)
91+
node = maxChild
92+
}
93+
}
94+
}
95+
96+
// another
97+
198
/**
299
* @param {number[][]} heights
3100
* @return {number}

0 commit comments

Comments
 (0)