1631. Path With Minimum Effort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Solution {
private static class UnionFind{
private final int[] parent;

public UnionFind(int n) {
this.parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}

public void union(int x, int y) {
int xRoot = getRoot(x), yRoot = getRoot(y);
if (xRoot == yRoot) {
return;
}

parent[xRoot] = yRoot;
}

private int getRoot(int x) {
if (x != parent[x]) {
int root = getRoot(parent[x]);
parent[x] = root;
}

return parent[x];
}

public boolean isConnected(int x, int y) {
return getRoot(x) == getRoot(y);
}
}

private static class Point {
private final int i;
private final int j;

public Point(int i, int j) {
this.i = i;
this.j = j;
}
}

private static class Edge {
private final Point a;
private final Point b;
private final int weight;

public Edge(Point a, Point b, int weight) {
this.a = a;
this.b = b;
this.weight = weight;
}
}

public int minimumEffortPath(int[][] heights) {
int m = heights.length, n = heights[0].length;

List<Edge> edgeList = new ArrayList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
Point a = new Point(i, j);
// 创建该点右侧与下方的边
if (j + 1 < n) {
edgeList.add(new Edge(a, new Point(i, j + 1), Math.abs(heights[i][j + 1] - heights[i][j])));
}
if (i + 1 < m) {
edgeList.add(new Edge(a, new Point(i + 1, j), Math.abs(heights[i + 1][j] - heights[i][j])));
}
}
}

edgeList.sort(Comparator.comparingInt(o -> o.weight));

UnionFind unionFind = new UnionFind(m * n);
Point startPoint = new Point(0, 0), endPoint = new Point(m - 1, n - 1);

for (Edge edge : edgeList) {
unionFind.union(getIndex(n, edge.a), getIndex(n, edge.b));
if (unionFind.isConnected(getIndex(n, startPoint), getIndex(n, endPoint))) {
return edge.weight;
}
}

return 0;
}

private int getIndex(int n, Point point) {
return point.i * n + point.j; // 注意此处是乘以列数
}
}

References

1631. Path With Minimum Effort