graph.algorithm.PrimJarnikMSTAlgorithm 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
The newest version!
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.Position;
import graph.util.PriorityQueue;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
public class PrimJarnikMSTAlgorithm extends AbstractGraphAlgorithm {
@SuppressWarnings("rawtypes")
private class PrimJarnikMSTOverlay implements GraphOverlay {
@Override
public Color edgeColor(Edge edge) {
for (Edge e : parentMap.values()) {
if (edge.equals(e)) return Color.RED;
}
return Color.BLACK;
}
@Override
public Color vertexColor(Vertex vertex) {
return Color.RED;
}
}
private Graph G;
private Map, Integer> distanceMap;
private Map, Position>> positionMap;
private Map, Edge> parentMap;
public PrimJarnikMSTAlgorithm() {
super();
distanceMap = new HashMap, Integer>();
positionMap = new HashMap, Position>>();
parentMap = new HashMap, Edge>();
}
public PrimJarnikMSTAlgorithm(Graph graph) {
this();
G = graph;
}
public void setGraph(Graph graph) {
G = graph;
}
public void search(Map> parameters) {
Vertex s = G.vertices().first().element();
List> cloud = new LinkedList>();
PriorityQueue> Q = new Heap>();
distanceMap.clear();
parentMap.clear();
for (Vertex vertex: G.vertices()) {
int value = Integer.MAX_VALUE;
if (vertex.equals(s)) value = 0;
distanceMap.put(vertex, value);
Position> p = Q.insert(value, vertex);
positionMap.put(vertex, p);
}
while (!Q.isEmpty()) {
Vertex u = Q.remove();
cloud.insertLast(u);
for (Edge e : G.incidentEdges(u)) {
Vertex z = G.opposite(u, e);
if (!inCloud(cloud, z)) {
int r = Integer.parseInt(e.element().toString());
if (r < distanceMap.get(z)) {
distanceMap.put(z, r);
parentMap.put(z, e);
Q.replaceKey(positionMap.get(z), r);
}
}
}
}
}
private boolean inCloud(List> cloud, Vertex z) {
for (Vertex vertex : cloud) {
if (vertex.equals(z)) return true;
}
return false;
}
@Override
public GraphOverlay getOverlay() {
return new PrimJarnikMSTOverlay();
}
}