-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtopologicalSort.cpp
More file actions
53 lines (40 loc) · 877 Bytes
/
topologicalSort.cpp
File metadata and controls
53 lines (40 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// using stack
#include<bits/stdc++.h>
using namespace std;
void topSortUtil(int v, bool visited[], stack<int> &Stack, vector<vector<int> > graph){
visited[v] = true;
for(int i = 0; i < graph[v].size(); i++){
if(visited[graph[v][i]] == false){
topSortUtil(graph[v][i],visited,Stack,graph);
}
}
Stack.push(v);
}
void topSort(vector<vector<int> > graph, int V, int E){
stack<int> Stack;
bool *visited = new bool[V];
for(int i = 0; i < V; i++){
visited[i] = false;
}
for(int i = 0; i < V; i++){
if(visited[i] == false){
topSortUtil(i,visited,Stack,graph);
}
}
// prine ordewr
while(Stack.empty() == false){
cout<<Stack.top()<<" ";
Stack.pop();
}
}
int main(){
int V;cin>>V;
int E;cin>>E;
vector<vector<int> > graph(V);
for(int i = 0; i < E; i++){
int u;cin>>u;
int v;cin>>v;
graph[u].push_back(v);
}
topSort(graph,V,E);
}