graph.algorithm.DijkstraShortestPathTreeAlgorithm 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.Parameter;
import graph.core.Vertex;
import graph.gui.GraphOverlay;
import graph.util.Heap;
import graph.util.Position;
import graph.util.PriorityQueue;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
public class DijkstraShortestPathTreeAlgorithm extends AbstractGraphAlgorithm {
@SuppressWarnings("rawtypes")
private class DijkstraOverlay 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 DijkstraShortestPathTreeAlgorithm() {
super();
distanceMap = new HashMap, Integer>();
positionMap = new HashMap, Position>>();
parentMap = new HashMap, Edge>();
addParameter(new Parameter("s","Give the start parameter for the algorithm"));
}
public graph.util.List> getRouteTo(Vertex target) {
graph.util.List> list = new graph.util.LinkedList>();
Vertex current = target;
list.insertFirst(target);
while (parentMap.get(current) != null) {
Edge edge = parentMap.get(current);
Vertex[] ends = G.endVertices(edge);
if (ends[0].equals(current)) {
list.insertFirst(ends[1]);
current = ends[1];
} else {
list.insertFirst(ends[0]);
current = ends[0];
}
}
return list;
}
public DijkstraShortestPathTreeAlgorithm(Graph graph) {
this();
G = graph;
}
public void setGraph(Graph graph) {
G = graph;
}
public void search(Map> parameters) {
Vertex s = parameters.get("s");
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();
for (Edge e : G.incidentEdges(u)) {
Vertex z = G.opposite(u, e);
int weight = Integer.parseInt((String) e.element());
if (weight != -1) {
int r = distanceMap.get(u) + weight;
if (r < distanceMap.get(z)) {
distanceMap.put(z, r);
Q.replaceKey(positionMap.get(z), r);
parentMap.put(z, e);
}
}
}
}
}
@Override
public GraphOverlay getOverlay() {
return new DijkstraOverlay();
}
}