graph.algorithm.KruskalMSTAlgorithm Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of astra-compiler Show documentation
Show all versions of astra-compiler Show documentation
Core compiler artifact for the ASTRA Language
package graph.algorithm;
import graph.core.AbstractGraphAlgorithm;
import graph.core.Edge;
import graph.core.Graph;
import graph.core.Vertex;
import graph.gui.GraphOverlay;
import graph.util.LinkedList;
import graph.util.Heap;
import graph.util.List;
import graph.util.PriorityQueue;
import java.awt.Color;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class KruskalMSTAlgorithm extends AbstractGraphAlgorithm {
@SuppressWarnings("rawtypes")
private class KruskalMSTOverlay implements GraphOverlay {
@Override
public Color edgeColor(Edge edge) {
for (Edge e: T) {
if (e.equals(edge)) return Color.RED;
}
return Color.BLACK;
}
@Override
public Color vertexColor(Vertex vertex) {
return Color.RED;
}
}
private Graph G;
private List> T;
private Map, List>> cloudMap;
private PriorityQueue> Q;
public KruskalMSTAlgorithm() {
super();
}
public KruskalMSTAlgorithm(Graph graph) {
this();
G = graph;
}
public void setGraph(Graph graph) {
G = graph;
}
public void search(Map> parameters) {
T = new LinkedList>();
cloudMap = new HashMap, List>>();
Q = new Heap>();
for (Vertex vertex: G.vertices()) {
List> list = new LinkedList>();
list.insertLast(vertex);
cloudMap.put(vertex, list);
}
for (Edge edge : G.edges()) {
Q.insert(Integer.parseInt(edge.toString()), edge);
}
int n = G.vertices().size();
while (T.size() < n - 1) {
Edge e = Q.remove();
Vertex[] endpoints = G.endVertices(e);
if (!cloudMap.get(endpoints[0]).equals(cloudMap.get(endpoints[1]))) {
T.insertLast(e);
Iterator> it = cloudMap.get(endpoints[1]).iterator();
while (!it.hasNext()) {
cloudMap.get(endpoints[0]).insertLast(it.next());
}
cloudMap.put(endpoints[1], cloudMap.get(endpoints[0]));
}
}
}
@Override
public GraphOverlay getOverlay() {
return new KruskalMSTOverlay();
}
}