-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalAlgorithm.java
More file actions
53 lines (43 loc) · 1.69 KB
/
Copy pathKruskalAlgorithm.java
File metadata and controls
53 lines (43 loc) · 1.69 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
import java.util.*;
public class KruskalAlgorithm {
private Graph graph;
public KruskalAlgorithm(Graph graph) {
this.graph = graph;
}
public MSTResult findMST() {
List<Edge> result = new ArrayList<>();
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(Edge::getWeight));
pq.addAll(graph.getEdges());
Map<Vertex, Vertex> parent = new HashMap<>();
for (Vertex v : graph.getVertices()) {
parent.put(v, v);
}
StringBuilder steps = new StringBuilder();
int totalWeight = 0;
while (!pq.isEmpty() && result.size() < graph.getVertices().size() - 1) {
Edge edge = pq.poll();
Vertex x = find(parent, edge.getSource());
Vertex y = find(parent, edge.getDestination());
if (x != y) {
result.add(edge);
totalWeight += edge.getWeight();
union(parent, x, y);
steps.append("Added edge: ").append(edge.getSource().getId())
.append(" - ").append(edge.getDestination().getId())
.append(" (").append(edge.getWeight()).append(")\n");
}
}
return new MSTResult(result, totalWeight, steps.toString());
}
private Vertex find(Map<Vertex, Vertex> parent, Vertex vertex) {
if (parent.get(vertex) != vertex) {
parent.put(vertex, find(parent, parent.get(vertex)));
}
return parent.get(vertex);
}
private void union(Map<Vertex, Vertex> parent, Vertex x, Vertex y) {
Vertex xRoot = find(parent, x);
Vertex yRoot = find(parent, y);
parent.put(xRoot, yRoot);
}
}