开发者

Odd ordering in iterative DFS vs recursive DFS

开发者 https://www.devze.com 2023-04-11 13:22 出处:网络
I\'m solving this dfs/bfs problem. I wrote both an iterative version and a recursive version of DFS.

I'm solving this dfs/bfs problem.

I wrote both an iterative version and a recursive version of DFS.

The order of node visiting is different and I don't get why.

iterative DFS:

static void DFS (Integer root, Graph graph){

      //  System.out.println("DFS");

        HashSet <Integer> explored = new HashSet<Integer>();
             explored.add(root);

        Stack<Integer> stack = new Stack<Integer>();
              stack.add(root);

        int v; int w;


        while (!stack.isEmpty()){

            v=stack.pop();
            explored.add(v);

            System.out.print(v + " ");
           // for (int i=graph.adjacencies.get(v).size()-1; i>=0; i--) {
            for (int i=0; i < graph.adjacencies.get(v).size(); i++) {
                w = graph.adjacencies.get(v).get(i);

                if (!explored.contains(w)){

                    stack.add(w);
                    explored.add(w);
                }
            }

        }System.out.println();
    } 

recursive DFS:

static void DFS_2 (Integer root, Graph graph){

//        System.out.println("DFS_2");

        int v; int w;

        v = root;

        graph.explored.add(v);

            System.out.print(v + " ");
            for (int i=0; i < graph.adjacencies.get(v).size(); i++) {

                w = graph.adjacencies.get(v).get(i);

                if (!graph.explored.contains(w)){

                    graph.explored.add(w);
                    DFS_2(w, graph);
                }
            }


    }

On 开发者_如何学Gothe tutorial problem my output on the iterative DFS version is

1 4 3 2 6

while it should be (according to the problem sample output and the recursive version):

1 3 2 6 4

What's happening here? Why is eliminating the recursion altering the visited node order?

->Full code on a Netbeans project.


Check your graph.adjacencies.get(V), does they give you the same response for the both cases? If so, then recursive call and stack call will give different results. For example, a tree like:

      1
    2   3
  4

will have the order 1->3->2->4 for the stack version, and the order of 1->2->4->3 for the recursive version, assuming graph.adjacencies.get(V) always returns the left child first.


Because of the Stack. It is First-In, Last-Out, so you'll be going through a nodes' children in the reversed order in which you added them to the stack.

Say the 2 kids of the root are A and B, in this order (left-to-right).

First algo:

  1. Handle root
  2. Add A to stack
  3. Add B to stack
  4. Pop from stack (so B, because the stack is FILO)

Second algo:

  1. Handle root
  2. Handle A
  3. ... handle A's kids
  4. Handle B

You can replace your Stack with a Queue implementation that is FIFO and it should be ok.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号