-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLc1631.java
More file actions
81 lines (75 loc) · 2.01 KB
/
Lc1631.java
File metadata and controls
81 lines (75 loc) · 2.01 KB
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
package leetcode;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Kuma
* @date 2021年2月19日
* 1631.最小体力消耗路径
*/
public class Lc1631 {
public int minimumEffortPath(int[][] heights) {
List<graph> g = new LinkedList<>();
int row = heights.length;
int col = heights[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if(i + 1 < row){
g.add(new graph(i * col + j,(i+1) * col + j,heights[i][j] - heights[i + 1][j]));
}
if (j + 1 < col){
g.add(new graph(i * col + j,i * col + j + 1,heights[i][j] - heights[i][j + 1]));
}
}
}
g.sort(Comparator.comparingInt(o -> o.weight));
UnionFind uf = new UnionFind(row * col);
for (graph i : g){
uf.union(i.x,i.y);
if (uf.check(0,row * col - 1)){
return i.weight;
}
}
return 0;
}
class graph{
int x;
int y;
int weight;
public graph(int x, int y, int weight) {
this.x = x;
this.y = y;
this.weight = Math.abs(weight);
}
}
class UnionFind{
int[] parent;
int count;
UnionFind(int k){
count = k;
parent = new int[k];
for (int i = 0; i < k; i++) {
parent[i] = i;
}
}
int find(int x){
while (x != parent[x]){
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY){
return;
}
parent[rootX] = rootY;
count--;
}
boolean check(int x,int y){
return find(x) == find(y);
}
}
}