Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // removing elements starting from indegree 0 till all are removed.. if count_of_removed elements = vertices .. no cycle exists
- vector<int> topoSort(int V, vector<int> adj[])
- {
- int indeg[V];
- for(int a=0;a<V;a++){
- for(int x : adj[a]){
- indeg[x]++;
- }
- }
- queue<int> q;
- for(int a=0;a<V;a++){
- if(indeg[a] == 0){
- q.push(a);
- }
- }
- vector<int> topo;
- int count =0;// visited nodes
- while(!q.empty()){
- int top = q.front();
- q.pop();
- topo.push_back(top);
- count ++;
- for(int x : adj[top]){
- indeg[x]--; // because we removed element with indegree 0 (at q.front())
- if(indeg[x] == 0)q.push(x);
- }
- }
- if(count != V) return {}; // cycle exists
- return topo ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement