Topological sort using DFS without recursion

后端 未结 7 1560
悲哀的现实
悲哀的现实 2020-12-24 14:37

I know the common way to do a topological sort is using DFS with recursion. But how would you do it using stack instead of recursion? I need to obtai

7条回答
  •  情深已故
    2020-12-24 15:05

    In order to construct the postOrder list you need to know the time when your algorithm has finished processing the last child of node k.

    One way to figure out when you have popped the last child off the stack is to put special marks on the stack to indicate spots where the children of a particular node are starting. You could change the type of your dfs stack to vector >. When the bool is set to true, it indicates a parent; false indicates a child.

    When you pop a "child pair" (i.e. one with the first member of the pair set to false) off the stack, you run the code that you currently have, i.e. push all their children onto the stack with your for loop. Before entering the for loop, however, you should push make_pair(true, node) onto the stack to mark the beginning of all children of this node.

    When you pop a "parent pair" off the stack, you push the parent index onto the postOrder, and move on:

    vector visited(MAX);
    stack > dfs;
    stack postOrder;
    vector newVec;
    vector::iterator it;
    vector > graph;
    for(int i=0;i node=dfs.top();
            dfs.pop();
            if (node.first) {
                postOrder.push(node.second);
                continue;
            }
            visited[node.second]=true;
            dfs.push(make_pair(true, node.second));
            newVec=graph[node.second]; //vector of neighboors
            for(it=newVec.begin();it!=newVec.end();it++){
                int son=*it;
                if(visited[son]==false){
                    dfs.push(make_pair(false, son));
                }
            }
        }
    }
    

    Demo on ideone.

提交回复
热议问题