简体   繁体   English

Graph中基于非递归堆栈的深度优先搜索未按顺序返回结果

[英]Non recursive stack based depth fIrst search in Graph returning results out of order

I am trying to recreate a recursive DFS using stacks, and of course being nonrecursive. 我正在尝试使用堆栈重新创建递归DFS,并且当然是非递归的。 I have tried re-coding this about four times and am stumped. 我已经尝试将其重新编码大约四次而感到困惑。 I have seen a lot of other people working with DFS, but not with this problem from what I can see. 我已经看到很多其他人在使用DFS,但从我所见,并没有解决这个问题。 The output is: 输出为:

12 vertices are searched in this DFS order:
Chicago New York Atlanta Houston Dallas Kansas City Denver Los Angeles San Francisco Seattle Miami Boston
parent of Seattle is San Francisco
parent of San Francisco is Los Angeles
parent of Los Angeles is Denver
parent of Denver is Kansas City
parent of Kansas City is Dallas
parent of Boston is Miami
parent of New York is Chicago
parent of Atlanta is New York
parent of Miami is Seattle
parent of Dallas is Houston
parent of Houston is Atlanta

When it should be: 什么时候应该是:

12 vertices are searched in this DFS order:  
Chicago Seattle San Francisco Los Angeles Denver   
Kansas City New York Boston Atlanta Miami Houston Dallas 
parent of Seattle is Chicago 
parent of San Francisco is Seattle 
parent of Los Angeles is San Francisco 
parent of Denver is Los Angeles 
parent of Kansas City is Denver 
parent of Boston is New York 
parent of New York is Kansas City 
parent of Atlanta is New York 
parent of Miami is Atlanta 
parent of Dallas is Houston 
parent of Houston is Miami 

Code

public Tree dfs(int v) {
    List<Integer> searchOrder = new ArrayList<>();
    int[] parent = new int[vertices.size()];
    for (int i = 0; i < parent.length; i++)
      parent[i] = -1; // Initialize parent[i] to -1

    // Mark visited vertices
    boolean[] isVisited = new boolean[vertices.size()];

    // Recursively search
    dfs(v, parent, searchOrder, isVisited);

    // Return a search tree
    return new Tree(v, parent, searchOrder);
  }

  /** Recursive method for DFS search */
  private void dfs(int u, int[] parent, List<Integer> searchOrder,
      boolean[] isVisited) {
    // Store the visited vertex
    Stack<Edge> stack = new Stack<>();
    isVisited[u] = true; // Vertex v visited
    searchOrder.add(u);
    for(Edge e : neighbors.get(u)){
      stack.push(e);
    }

    while (!stack.isEmpty()) {
      Edge e = stack.pop();
      if (!isVisited[e.v]) {
        parent[e.v] = u; // The parent of vertex e.v is u
        isVisited[e.v] = true;
        searchOrder.add(e.v);
        u = e.v;
        for(Edge d : neighbors.get(u)){
          stack.push(d);
        }
      }
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM