All Downloads are FREE. Search and download functionalities are using the official Maven repository.

graph.algorithm.DepthFirstSearchAlgorithm Maven / Gradle / Ivy

There is a newer version: 1.4.3
Show newest version
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();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy