Skip to content

Commit 4085dcf

Browse files
committed
https://leetcode.cn/problems/path-with-minimum-effort
1 parent 5af8d23 commit 4085dcf

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Step 2. Add the dependency
4949

5050
<summary>展开查看</summary>
5151

52+
https://leetcode.cn/problems/path-with-minimum-effort
53+
5254
https://leetcode.cn/problems/last-day-where-you-can-still-cross/
5355

5456
https://leetcode.cn/problems/bricks-falling-when-hit/

path-with-minimum-effort/index.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { UnionFind } from "../largest-component-size-by-common-factor/UnionFind.ts";
2+
function minimumEffortPath(heights: number[][]): number {
3+
const edges: [number, number, number][] = [];
4+
const N = heights.length;
5+
const M = heights[0].length;
6+
if (N == 1 && M == 1) return 0;
7+
for (let i = 0; i < N; ++i) {
8+
for (let j = 0; j < M; ++j) {
9+
if (j + 1 < M) {
10+
edges.push([
11+
Math.abs(heights[i][j] - heights[i][j + 1]),
12+
i * M + j,
13+
i * M + j + 1,
14+
]);
15+
}
16+
if (i + 1 < N) {
17+
edges.push([
18+
Math.abs(heights[i][j] - heights[i + 1][j]),
19+
i * M + j,
20+
(i + 1) * M + j,
21+
]);
22+
}
23+
}
24+
}
25+
edges.sort((a, b) => a[0] - b[0]);
26+
const dsu = new UnionFind();
27+
let i = 0;
28+
while (dsu.find(0) != dsu.find(N * M - 1)) {
29+
dsu.union(edges[i][1], edges[i][2]);
30+
i++;
31+
}
32+
return edges[i - 1][0];
33+
}
34+
export default minimumEffortPath;

0 commit comments

Comments
 (0)