graph.algorithm.DijkstraShortestPathAlgorithm 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.Parameter;
import graph.core.Vertex;
import graph.gui.GraphOverlay;
import graph.util.Heap;
import graph.util.LinkedList;
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 DijkstraShortestPathAlgorithm extends AbstractGraphAlgorithm {
@SuppressWarnings("rawtypes")
private class DijkstraOverlay implements GraphOverlay {
@Override
public Color edgeColor(Edge edge) {
for (Edge e : spEdgeList) {
if (edge.equals(e)) return Color.RED;
}
return Color.BLACK;
}
@Override
public Color vertexColor(Vertex vertex) {
for (Vertex v : spVertexList) {
if (vertex.equals(v)) return Color.RED;
}
return Color.BLACK;
}
}
private List> spVertexList;
private List> spEdgeList;
private Graph G;
private Map, Integer> distanceMap;
private Map, Position>> positionMap;
private Map, Edge> parentMap;
public DijkstraShortestPathAlgorithm() {
super();
distanceMap = new HashMap, Integer>();
positionMap = new HashMap, Position>>();
parentMap = new HashMap, Edge>();
addParameter(new Parameter("s","Give the start vertex for the algorithm"));
addParameter(new Parameter("e","Give the end vertex for the algorithm"));
}
public DijkstraShortestPathAlgorithm(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>();
spVertexList = new LinkedList>();
spEdgeList = new LinkedList>();
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 r = distanceMap.get(u) + Integer.parseInt(e.element().toString());
if (r < distanceMap.get(z)) {
distanceMap.put(z, r);
Q.replaceKey(positionMap.get(z), r);
parentMap.put(z, e);
}
}
}
// Work out shortest path
// NOTE: This is the only change to the STP algorithm
Vertex v = parameters.get("e");
while (!v.equals(s)) {
spVertexList.insertFirst(v);
Edge e = parentMap.get(v);
spEdgeList.insertFirst(e);
v = G.opposite(v, e);
}
spVertexList.insertFirst(v);
}
@Override
public GraphOverlay getOverlay() {
return new DijkstraOverlay();
}
}