Topological sort using DFS without recursion

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

    The Graph structure is as folows

    N: number of vertices adj[]: input graph

    vector<int> topoSort(int V, vector<int> adj[]) {
        stack<int> s;
        vector<int> f(V,0);
        
        stack<int> out; 
        int i,j,x;
        for(i=0;i<V;i++){
            if(f[i]==0){
                s.push(i);
                
                while(!s.empty()){
                    x = s.top();
                    s.pop();
                    if(f[x]==1){
                        out.push(x);
                        continue;
                    }
                    f[x] = 1;
                    s.push(x);
                    for(j=0;j<adj[x].size();j++){
                        if(f[adj[x][j]]==0){
                            s.push(adj[x][j]);
                        }
                    }
                }
            }
        }
        
        vector<int> output;
    
        while(!out.empty()){
            x=out.top();
            out.pop();
            //cout << x << " ";
            output.push_back(x);
        }
        //cout << endl;
        
        return output;
    }
    
    0 讨论(0)
提交回复
热议问题