Skip to content

Commit 52e528b

Browse files
authored
Topological Sort added
1 parent c40ba46 commit 52e528b

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
//Topological Sorting of directed and acyclic graph.
2+
//It is done by BFS and using in_degree array.
3+
//It has one property that it returns the sorting in lexographical order.
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
7+
int vertices,edges;
8+
vector<int>adjcency_list[100001];
9+
10+
vector<int> topological_sort(){
11+
vector<int> topo;
12+
int in_degree[vertices+1];
13+
bool visited[vertices+1];
14+
priority_queue<int,vector<int>,greater<int>> q;
15+
16+
for(int i=1;i<=vertices;i++){
17+
visited[i]=false;
18+
in_degree[i]=0;
19+
}
20+
21+
for(int i=1;i<=vertices;i++){
22+
for(int j:adjcency_list[i]){
23+
in_degree[j]=in_degree[j]+1;
24+
}
25+
}
26+
27+
for(int i=1;i<=vertices;i++){
28+
if(in_degree[i]==0){
29+
visited[i]=true;
30+
q.push(i);
31+
}
32+
}
33+
int k=0;
34+
while(!q.empty()){
35+
int v=q.top();
36+
q.pop();
37+
topo.push_back(v);
38+
for(int i:adjcency_list[v]){
39+
if(visited[i]==false){
40+
in_degree[i]=in_degree[i]-1;
41+
if(in_degree[i]==0){
42+
q.push(i);
43+
visited[i]=true;
44+
}
45+
}
46+
}
47+
}
48+
return topo;
49+
}
50+
51+
int main(){
52+
cout<<"Enter number of vertices and edges:\n";
53+
cin>>vertices>>edges;
54+
55+
vector<int> topological_sorted;
56+
57+
cout<<"Enter the edges directed from X (first number) to Y (second number):\n";
58+
for(int i=0;i<edges;i++){
59+
int u,v;
60+
cin>>u>>v;
61+
adjcency_list[u].push_back(v);
62+
}
63+
64+
topological_sorted=topological_sort();
65+
66+
cout<<"Topological Sort of the given graph: ";
67+
for(int i=0;i<topological_sorted.size();i++){
68+
cout<<topological_sorted[i]<<" ";
69+
}
70+
cout<<"\n";
71+
return 0;
72+
}

0 commit comments

Comments
 (0)