Skip to content

Commit 0abe91a

Browse files
committed
minimumEffortPath
1 parent 4085dcf commit 0abe91a

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

deps.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ export { default as isEqual } from "https://cdn.skypack.dev/[email protected]/isEqu
1313
export { default as uniqBy } from "https://cdn.skypack.dev/[email protected]/uniqBy?dts";
1414

1515
export { default as intersection } from "https://cdn.skypack.dev/[email protected]/intersection?dts";
16-
16+
import { BinaryHeap } from "https://deno.land/[email protected]/collections/binary_heap.ts";
17+
export { BinaryHeap };
1718
export { walk } from "https://deno.land/[email protected]/fs/mod.ts";
1819
export { parse } from "https://deno.land/[email protected]/flags/mod.ts";
1920
export { combinations } from "https://deno.land/x/[email protected]/mod.ts";
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { BinaryHeap } from "https://deno.land/[email protected]/collections/binary_heap.ts";
2+
3+
function minimumEffortPath(heights: number[][]): number {
4+
const dirs = [
5+
[-1, 0],
6+
[1, 0],
7+
[0, -1],
8+
[0, 1],
9+
];
10+
11+
const m = heights.length;
12+
const n = heights[0].length;
13+
const pq = new BinaryHeap<[number, number, number]>(
14+
(edge1, edge2) => edge1[2] - edge2[2],
15+
);
16+
pq.push([0, 0, 0]);
17+
18+
const dist = new Array<number>(m * n);
19+
dist.fill(Infinity);
20+
dist[0] = 0;
21+
const seen = new Array<boolean>(m * n);
22+
23+
while (!pq.isEmpty()) {
24+
const edge = pq.pop() as [number, number, number];
25+
const x = edge[0],
26+
y = edge[1],
27+
d = edge[2];
28+
const id = x * n + y;
29+
if (seen[id]) {
30+
continue;
31+
}
32+
if (x == m - 1 && y == n - 1) {
33+
break;
34+
}
35+
seen[id] = true;
36+
for (let i = 0; i < 4; ++i) {
37+
const nx = x + dirs[i][0];
38+
const ny = y + dirs[i][1];
39+
if (
40+
nx >= 0 &&
41+
nx < m &&
42+
ny >= 0 &&
43+
ny < n &&
44+
Math.max(d, Math.abs(heights[x][y] - heights[nx][ny])) <
45+
dist[nx * n + ny]
46+
) {
47+
dist[nx * n + ny] = Math.max(
48+
d,
49+
Math.abs(heights[x][y] - heights[nx][ny]),
50+
);
51+
pq.push([nx, ny, dist[nx * n + ny]]);
52+
}
53+
}
54+
}
55+
56+
return dist[m * n - 1];
57+
}
58+
export default minimumEffortPath;

0 commit comments

Comments
 (0)