Topological sort using DFS without recursion

后端 未结 7 1540
悲哀的现实
悲哀的现实 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:02

    Below is my iterative code to topological sorting of DAG.

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    unordered_map> g;  // this is the simplest graph representation I was able to implement. Map the vertices to their set of children
    
    void addEdge(int x, int y) { // Add edges to the graph
        g[x].insert(y);
    }
    
    void topSort() {
        unordered_set visited; // Keep track of visited nodes
        stack mainStack; // The stack that will have the resulting vertices in topologically sorted order
    
        for(auto it = g.begin(); it != g.end(); it++) {
            if(visited.count(it->first) == 0) { // If the vertex was not already visited do the following
                visited.insert(it->first); // visit the vertex
                stack locStack;
                locStack.push(it->first); // push it to local stack
                while(!locStack.empty()) { // This part is similar to basic DFS algorithm
                    int curr = locStack.top();
                    bool unVisCh = false; // Keep a boolean to check whether there is any unvisited child
                    for(auto it2 = g[curr].begin(); it2 != g[curr].end(); it2++) {
                        int child = *it2;
                        if(visited.count(child) == 0) {
                            unVisCh = true;
                            visited.insert(child);
                            locStack.push(child);
                        }
                    }
                    if(!unVisCh) { // if there is no unvisited child then we can push the vertex to the resulting stack
                        locStack.pop();
                        mainStack.push(curr);
                    }
                }
            }
        }
    
        while(!mainStack.empty()) {
            cout<

    For testing: ideone

提交回复
热议问题