-
Notifications
You must be signed in to change notification settings - Fork 488
/
KruskalsMST.java
87 lines (78 loc) · 2.17 KB
/
KruskalsMST.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
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
package util.graph;
import java.util.Arrays;
/**
* Kruskal's minimum spanning tree algorithm
* @author Andrew Guillory gtg008g@mail.gatech.edu
* @version 1.0
*/
public class KruskalsMST implements GraphTransformation {
/**
* The ranks of the nodes
*/
private int[] ranks;
/**
* The paths of the nodes
*/
private int[] paths;
/**
* @see graph.GraphTransform#transform(graph.Graph)
*/
public Graph transform(Graph g) {
WeightedEdge[] edges = (WeightedEdge[]) g.getEdges().toArray(new WeightedEdge[0]);
Arrays.sort(edges);
for (int i = 0; i < g.getNodeCount(); i++) {
g.getNode(i).getEdges().clear();
}
ranks = new int[g.getNodeCount()];
paths = new int[g.getNodeCount()];
for (int i = 0; i < g.getNodeCount(); i++) {
ranks[i] = 0;
paths[i] = i;
}
for (int i = 0; i < edges.length; i++) {
int in = edges[i].getA().getLabel();
int out = edges[i].getB().getLabel();
if (set(in) != set(out)) {
combine(in, out);
g.getNode(in).connect(g.getNode(out), edges[i]);
}
}
ranks = null;
paths = null;
return g;
}
/**
* Find the set label for a given index
* @param i the set label to find
* @return the root label of the set
*/
private int set(int i) {
if (paths[i] != i) {
paths[i] = set(paths[i]);
}
return paths[i];
}
/**
* Combine two the sets
* @param i the first set to combine
* @param j the second to combine
*/
private void combine(int i, int j) {
link(set(i), set(j));
}
/**
* Link together two sets
* @param i the first set
* @param j the second set
*/
private void link(int i, int j) {
if (ranks[i] > ranks[j]) {
paths[j] = i;
} else {
paths[i] = j;
if (ranks[i] == ranks[j]) {
ranks[j]++;
}
}
}
}