深度优先搜索之寻找路径

算法思想:数组edgeTo数组记录的值是当前结点,下标为其邻接点(即路径的下一个结点)

public class DepthFirstSearch {
    private boolean[] marked;
    private int[] edgeTo;//从起点到一个顶点的已知路径上的最后一个点
    private final int s;//起点

    public DepthFirstSearch(Graphics G,int s){
        marked = new boolean[G.v()];
        edgeTo = new int[G.v()];
        this.s = s;
        dfs(G,s);
    }

    private void dfs(Graphics G, int v) {
        marked[v] = true;//标记遍历过的顶点
        for(int w:G.adj(v)){
            if(!marked[w]){
                edgeTo[w] = v;
                dfs(G,w);
            }
        }
    }

    public boolean hasPath(int v){
        return marked[v];   
    }

    public void path(int v,Vector vec){
        Stack stack = null;
        int p = v;

        while(p != s){
            stack.push(p);
            p = edgeTo[p];
        }

        vec.clear();
        while(!stack.empty()){
            vec.add(stack.peek());
            stack.pop();
        }
    }


}

你可能感兴趣的:(数据结构与算法)