美文网首页
DepthFirstPaths

DepthFirstPaths

作者: 賈小強 | 来源:发表于2018-04-07 10:48 被阅读0次

    简书 賈小強
    转载请注明原创出处,谢谢!

    package com.lab1.test4;
    
    import com.lab1.test1.LinkedStack;
    
    public class DepthFirstPaths {
        private boolean[] marked;
        private int[] edgeTo;
        private int s;
    
        public DepthFirstPaths(Graph graph, int s) {
            marked = new boolean[graph.V()];
            edgeTo = new int[graph.V()];
            this.s = s;
            dfs(graph, s);
        }
    
        private void dfs(Graph graph, int v) {
            marked[v] = true;
            for (int w : graph.adj(v)) {
                if (!marked[w]) {
                    edgeTo[w] = v;
                    dfs(graph, w);
                }
            }
        }
    
        private Iterable<Integer> pathTo(int v) {
            LinkedStack<Integer> stack = new LinkedStack<>();
            for (int x = v; x != s; x = edgeTo[x]) {
                stack.push(x);
            }
            stack.push(s);
            return stack;
        }
    
        private boolean hashPathTo(int v) {
            return marked[v];
        }
    
        public static void main(String[] args) {
            int[][] edges = { { 0, 5 }, { 2, 4 }, { 2, 3 }, { 1, 2 }, { 0, 1 }, { 3, 4 }, { 3, 5 }, { 0, 2 } };
            Graph graph = new Graph(edges);
            int s = 0;
            DepthFirstPaths dfs = new DepthFirstPaths(graph, s);
            for (int v = 0; v < graph.V(); v++) {
                if (dfs.hashPathTo(v)) {
                    System.out.print(s + " to " + v + " : ");
                    for (int x : dfs.pathTo(v)) {
                        System.out.print(x + " ");
                    }
                    System.out.println();
                } else {
                    System.out.println(s + " to " + v + "Not Connected");
                }
            }
        }
    
    }
    

    输出

    0 to 0 : 0 
    0 to 1 : 0 2 1 
    0 to 2 : 0 2 
    0 to 3 : 0 2 3 
    0 to 4 : 0 2 3 4 
    0 to 5 : 0 2 3 5 
    

    Happy learning !!

    相关文章

      网友评论

          本文标题:DepthFirstPaths

          本文链接:https://www.haomeiwen.com/subject/zkaehftx.html