无向图的处理算法(二)

767 查看

在图中,我们很自然地会问这几个问题

  • 从一个顶点s能否到达顶点v?
  • 以s为顶点能到达的所有顶点?

解决能否到达问题的算法就是深度优先算法,使用深度优先算法获得的从s到v的路径的时间与路径的长度成正比。

package Graph;

import java.util.Stack;

//基于深度优先算法,搜索查找图中的路径
//解决单点路径问题,即,从一点开始是否存在到另一个点的路径
public class DepthFirstPaths {
    private boolean[] marked;//这个顶点调用过dfs了吗
    private int[] edgeTo;//从起点到该点路径上的最后一个顶点
    private final int s;//起点

    public DepthFirstPaths(Graph g,int s)
    {
        marked = new boolean[g.V()];
        edgeTo = new int[g.V()];
        this.s = s;
        dfs(g,s);
    }

    private void dfs(Graph G,int V){
        marked[V] = true;
        for(int w: G.adj(V)){
            if(!marked[w]){
                edgeTo[w] = V;//表示这条路径上,w之前是v
                dfs(G,w);
            }
        }
    }

    public boolean hasPathTo(int V){
        return marked[V];
    }

    public Iterable<Integer> pathTo(int V){
        if(!hasPathTo(V)) return null;
        Stack<Integer> path = new Stack<Integer>();
        for(int x = V;x != s; x = edgeTo[x])//从终点开始往上回溯
            path.push(x);
        path.push(s);
        return path;

    }
}

这样通过调用pathTo(v)就可以知道到任意顶点v的路径。