in the following code I am trying to implement Kruskal's algorithm to compute the minimal spanning tree of a graph.
The problem is that removing sets from the connected components does not work properly and that the case if(!startSet.equals(endSet)) always seems to be executed.
Now the code:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.jgrapht.Graph;
import org.jgrapht.graph.AsSubgraph;
import org.jgrapht.graph.DefaultWeightedEdge;
import java.util.PriorityQueue;
public class mySpanningTree {
//Receives a graph and computes a minimum spanning tree
public static AsSubgraph<Integer, DefaultWeightedEdge> computeMST(Graph<Integer, DefaultWeightedEdge> graph) {
AsSubgraph<Integer, DefaultWeightedEdge> tree = new AsSubgraph<Integer, DefaultWeightedEdge>(graph, graph.vertexSet(), new HashSet<DefaultWeightedEdge>());
PriorityQueue<DefaultWeightedEdge> edgeQueue = new PriorityQueue<>(Comparator.comparingDouble(graph::getEdgeWeight));
edgeQueue.addAll(graph.edgeSet());
Set<Set<Integer>> connectedComponents = new HashSet<>();
for(Integer i : graph.vertexSet()){
Set<Integer> set = new HashSet<>();
set.add(i);
connectedComponents.add(set);
}
int n = tree.vertexSet().size() - 1;
while (!edgeQueue.isEmpty() && tree.edgeSet().size() < n) {
DefaultWeightedEdge edge = edgeQueue.poll();
Integer start = graph.getEdgeSource(edge);
Integer end = graph.getEdgeTarget(edge);
Set<Integer> startSet = null;
Set<Integer> endSet = null;
for(Set<Integer> set: connectedComponents){
if(set.contains(start)){
startSet = set;
}
if(set.contains(end)){
endSet = set;
}
}
if(!startSet.equals(endSet)){
startSet.addAll(endSet);
connectedComponents.remove(endSet);
tree.addEdge(start, end, edge);
}
else{
}
}
return tree;
}
The idea of the code is to keep track of the connected components in a set. Whenever an edge connects two nodes from different connected components, I want to union the two connected components and store the result inside the set instead of the two components from before. Furthermore, the edge shall be added. Whenever an edge has two endpoints in one and the same set, it shall not be added (since adding it would create a cycle).
Any help is appreciated!