Skip to content

Commit 9052720

Browse files
authored
Merge pull request larissalages#180 from ErR0rpj/master
Topological Sort (Graphs)
2 parents bc48a25 + 127d3d3 commit 9052720

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-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+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Code | Test
4343
[Quick Sort](https://github.com/kartikeysingh6/code_problems/blob/master/classical_algorithms/c++/quicksort.cpp) | Missing tests
4444
[0/1 Knapsack Problem](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp) | Missing tests
4545
[Kadane's Algorithm](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp) | Missing tests
46+
[Topological Sort](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Topological_sort.cpp) | Missing Tests
4647

4748
# Codeforces
4849

0 commit comments

Comments
 (0)