Two ways of implementation for Topological Sort

1. Use a stack

#define V 5

void TopologicalSortUtil(int v,vector> adj,vector& visited,stack& s){
    visited[v]=true;
    for(int it: adj[v]){
        if(!visited[v]) TopologicalSortUtil(it,adj,visited,s);
    }
    s.push(v);
}

void TopologicalSort(){
    //store all directed edges
    vector> adj;
    vector visited(V,false);
    stack s;
    for(int i=0;i

2. Use a queue

void TopologicalSort(){
    //store the predecessor of all nodes
    vector res;
    vector> predecessor;
    vector indegree;
    queue q;
    //find all nodes that the indegrees are 0
    //some nodes that don't have any predecessors have 0 indegree
    for(int i=0;i

 

 

你可能感兴趣的:(algorithm,graph,topological,sort)