Advertisement
Oppenheimer

topological sort BFS (Kahn algo) + (cycle detection in DAG)

Jul 15th, 2023 (edited)
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. // removing elements starting from indegree 0 till all are removed.. if count_of_removed elements = vertices .. no cycle exists
  2.  
  3. vector<int> topoSort(int V, vector<int> adj[])
  4.     {
  5.         int indeg[V];
  6.         for(int a=0;a<V;a++){
  7.             for(int x : adj[a]){
  8.                 indeg[x]++;
  9.             }
  10.         }
  11.         queue<int> q;
  12.         for(int a=0;a<V;a++){
  13.             if(indeg[a] == 0){
  14.                 q.push(a);
  15.             }
  16.         }
  17.         vector<int> topo;
  18.         int count =0;// visited nodes
  19.         while(!q.empty()){
  20.             int top = q.front();
  21.             q.pop();
  22.             topo.push_back(top);
  23.             count ++;
  24.            
  25.             for(int x : adj[top]){
  26.                 indeg[x]--; // because we removed element with indegree 0 (at q.front())
  27.                 if(indeg[x] == 0)q.push(x);
  28.             }
  29.         }
  30.         if(count != V) return {}; // cycle exists
  31.        
  32.         return topo ;
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement