graph.algorithm.DepthFirstSearchAlgorithm 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.GraphAlgorithm;
import graph.core.Vertex;
import graph.gui.GraphOverlay;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
public class DepthFirstSearchAlgorithm extends AbstractGraphAlgorithm {
@SuppressWarnings("rawtypes")
private class BreadthFirstOverlay implements GraphOverlay {
Map colorMap = new HashMap();
{
colorMap.put(GraphAlgorithm.UNEXPLORED, Color.BLACK);
colorMap.put(GraphAlgorithm.DISCOVERY, Color.RED);
colorMap.put(GraphAlgorithm.VISITED, Color.RED);
colorMap.put(GraphAlgorithm.BACK, Color.GREEN);
}
@Override
public Color edgeColor(Edge edge) {
return colorMap.get(edgeLabels.get(edge));
}
@Override
public Color vertexColor(Vertex vertex) {
return colorMap.get(vertexLabels.get(vertex));
}
}
private Graph G;
private Map, Integer> vertexLabels;
private Map, Integer> edgeLabels;
public DepthFirstSearchAlgorithm() {
super();
vertexLabels = new HashMap, Integer>();
edgeLabels = new HashMap, Integer>();
}
public DepthFirstSearchAlgorithm(Graph graph) {
this();
G = graph;
}
public void setGraph(Graph graph) {
G = graph;
}
public void search(Map> parameters) {
for (Vertex vertex: G.vertices()) {
vertexLabels.put(vertex, UNEXPLORED);
}
for (Edge edge: G.edges()) {
edgeLabels.put(edge, UNEXPLORED);
}
for (Vertex vertex: G.vertices()) {
if (vertexLabels.get(vertex) == UNEXPLORED) {
search(vertex);
}
}
}
public void search(Vertex s) {
vertexLabels.put(s, VISITED);
for (Edge e : G.incidentEdges(s)) {
if (edgeLabels.get(e) == UNEXPLORED) {
Vertex w = G.opposite(s, e);
if (vertexLabels.get(w) == UNEXPLORED) {
edgeLabels.put(e, DISCOVERY);
search(w);
} else {
edgeLabels.put(e, BACK);
}
}
}
}
@Override
public GraphOverlay getOverlay() {
return new BreadthFirstOverlay();
}
}