Java中的后序图遍历的迭代版本

时间:2019-07-19 06:31:13

标签: java algorithm

我正在寻找Java中图形后顺序遍历的迭代版本。我已经编写了执行迭代DFS的代码。我如何修改代码,以便以下代码可以打印出迭代后置DFS遍历的路径?例如,下图的输出应为FCBEDA(G)。

graph image

public void DFS(int sourceVertex) {
     Stack<Integer> stack = new Stack<>();
     stack.push(sourceVertex);
     while (!stack.isEmpty()) {
          int v = stack.pop();
          if (!marked[v]) {
               marked[v] = true;
               for (int w : v.adj) {
                    stack.push(w);
               }
          }
     }
}

2 个答案:

答案 0 :(得分:4)

您应尽可能深入然后将其放入后期订单列表中的方法是:

public LinkedList<Integer> postorder(Digraph digraph, int source) {

    Stack<Integer> stack = new Stack<>();
    LinkedList<Integer> postorder = new LinkedList<>();

    visited[source] = true;           // visited = new boolean[V], # of vertices
    stack.push(source);

    while (!stack.isEmpty()) {

        int cur = stack.peek();       // don't pop(), just peek(), we will pop() it 
        boolean tail = true;          // only if this vertex is tail
        for (Integer v : digraph.adj(cur)) {
            if (visited[v] == false) {
                tail = false;         // found one vertex that can be approached next
                visited[v] = true;    // then vertex cur is not tail yet 
                stack.push(v);
                break;                // one neighbor is found and that is enough, 
                                      // let's examine it in next peek(), others 
            }                         // will be found later
        }                             
        if (tail) {                   // we didn't enter for-loop above, then cur is 
            stack.pop();              // tail, we pop() it and add to postorder list
            postorder.addLast(cur);
        }

    }
    return postorder; 
}

代码中的注释应说明方法。

答案 1 :(得分:1)

您的图是有向图,您不能从F到任何其他节点,然后,F DFS 仅返回F节点。通常,当您使用不同的起始节点(并且图形是否有向)时,输出会有所不同。

迭代 DFS 算法可以写为:

static List<Node> DFS(Node n) {

    Stack<Node> current = new Stack<>();
    Set<Node> visited = new HashSet<>(); // efficient lookup
    List<Node> result = new ArrayList<>(); // ordered

    current.push(n);

    while(!current.isEmpty()) {
        Node c = current.pop();
        if(!visited.contains(c)) {
            result.add(c);
            visited.add(c);
            // push in reversed order
            IntStream.range(0, c.getChildren().size())
                    .forEach(i -> current.push(c.getChildren().get(c.getChildren().size() - i - 1)));
        }
    }

    return result;
}

您可以避免使用visited Set,但是使用result来检查节点是否被访问,而O(n)花费了Set (摊销)。

完整的示例:

O(1)

输出:

public static void main(String[] args) {

    Node A = new Node("A");
    Node B = new Node("B");
    Node C = new Node("C");
    Node D = new Node("D");
    Node E = new Node("E");
    Node F = new Node("F");
    Node G = new Node("G");

    A.getChildren().addAll(asList(B, D));
    B.getChildren().addAll(asList(C));
    C.getChildren().addAll(asList(F));
    D.getChildren().addAll(asList(B, F, E));
    E.getChildren().addAll(asList(F));
    //F.getChildren().addAll(asList());
    G.getChildren().addAll(asList(F));

    testDFS(F);
    testDFS(G);
    testDFS(A);

}

static class Node {
    private final String label;
    private final List<Node> children;

    Node(String label) {
        this.label = label;
        this.children = new ArrayList<>();
    }

    public String getLabel() {
        return label;
    }

    public List<Node> getChildren() {
        return children;
    }

    @Override
    public int hashCode() {
        return getLabel().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Node))
            return false;
        return getLabel().equals(((Node) obj).getLabel());
    }
}

如果您希望事后订购(首先显示最后一个访问的节点),则反转结果列表(或添加到标题等)。

要颠倒From 'F': F From 'G': G, F From 'A': A, B, C, F, D, E 的顺序,请在插入之前不要颠倒:

children

现在,您得到static List<Node> DFSreversedPostOrder(Node n) { Stack<Node> current = new Stack<>(); Set<Node> visited = new HashSet<>(); // efficient lookup List<Node> result = new ArrayList<>(); // ordered current.push(n); while(!current.isEmpty()) { Node c = current.pop(); if(!visited.contains(c)) { result.add(0, c); visited.add(c); c.getChildren().forEach(current::push); } } return result; }

CBFEDA

注意,您的示例是错误的,因为在From 'F': F From 'G': F, G From 'A': C, B, F, E, D, A 节点之后,您必须访问E而不是F