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

graph.algorithm.BreadthFirstSearchAlgorithm 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 graph.util.LinkedList;
import graph.util.List;

import java.awt.Color;
import java.util.HashMap;
import java.util.Map;

public class BreadthFirstSearchAlgorithm 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.CROSS, 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 BreadthFirstSearchAlgorithm() {
		super();
		vertexLabels = new HashMap, Integer>();
		edgeLabels = new HashMap, Integer>();
	}
	
	public BreadthFirstSearchAlgorithm(Graph graph) {
		this();
		G = graph;
	}
	
	public void setGraph(Graph graph) {
		G = graph;
	}
	
	@Override
	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) {
		List> current = new LinkedList>();
		current.insertLast(s);
		vertexLabels.put(s, VISITED);

		
		while (!current.isEmpty()) {
			List> next = new LinkedList>();
			for (Vertex v : current) {
				for (Edge e : G.incidentEdges(v)) {
					if (edgeLabels.get(e) == UNEXPLORED) {
						Vertex w = G.opposite(v, e);
						if (vertexLabels.get(w) == UNEXPLORED) {
							edgeLabels.put(e, DISCOVERY);
							vertexLabels.put(w, VISITED);
							next.insertLast(w);
						} else {
							edgeLabels.put(e, CROSS);
						}
					}
				}
			}
			current = next;
		}
	}

	@Override
	public GraphOverlay getOverlay() {
		return new BreadthFirstOverlay();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy