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

tk.hongkailiu.test.app.graph.DFSConnector Maven / Gradle / Ivy

The newest version!
package tk.hongkailiu.test.app.graph;

import org.apache.log4j.Logger;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;

/**
 * depth-first searching
 *
 * @author Liu
 */
public class DFSConnector implements Connector {

    Logger logger = Logger.getLogger(this.getClass());

    private Deque stack = new ArrayDeque();
    //private Deque stack = new LinkedList();

    private Graph graph;

    public DFSConnector(Graph graph) {
        super();
        this.graph = graph;
        this.graph.setConnector(this);
    }

    public DFSConnector() {
        super();
    }

    @Override public void setGraph(Graph graph) {
        this.graph = graph;
    }

    @Override public Set getConectedVertices(Vertex vertex) {
        Set set = new HashSet();

        stack.clear();
        cleanUpMarkers();

        Vertex vTemp = GraphUtil.getVertex(vertex, graph.vertices);
        stack.offer(vTemp);

        while (!stack.isEmpty()) {
            Vertex v = stack.pollLast();
            if (!v.isVisted()) {
                v.setVisted(true);
                logger.debug("v: " + v);
                set.add(v);
                Set adSet = graph.getAdjacentList().get(v);
                if (adSet != null) {
                    for (Vertex v1 : adSet) {
                        if (!v1.isVisted()) {
                            stack.offer(v1);
                        }
                    }
                }
            }

        }
        return set;
    }

    private void cleanUpMarkers() {
        for (Vertex v : graph.getVertices()) {
            v.setVisted(false);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy