-
Notifications
You must be signed in to change notification settings - Fork 104
/
Kruskal.java
47 lines (36 loc) · 1.12 KB
/
Kruskal.java
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Kruskal {
private WeightedGraph G;
private ArrayList<WeightedEdge> mst;
public Kruskal(WeightedGraph G){
this.G = G;
mst = new ArrayList<>();
CC cc = new CC(G);
if(cc.count() > 1) return;
ArrayList<WeightedEdge> edges = new ArrayList<>();
for(int v = 0; v < G.V(); v ++)
for(int w: G.adj(v))
if(v < w)
edges.add(new WeightedEdge(v, w, G.getWeight(v, w)));
Collections.sort(edges);
UF uf = new UF(G.V());
for(WeightedEdge edge: edges){
int v = edge.getV();
int w = edge.getW();
if(!uf.isConnected(v, w)){
mst.add(edge);
uf.unionElements(v, w);
}
}
}
public ArrayList<WeightedEdge> result(){
return mst;
}
public static void main(String[] args){
WeightedGraph g = new WeightedGraph("g.txt");
Kruskal kruskal = new Kruskal(g);
System.out.println(kruskal.result());
}
}