-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.cpp
More file actions
69 lines (53 loc) · 1.05 KB
/
TopologicalSort.cpp
File metadata and controls
69 lines (53 loc) · 1.05 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<bits/stdc++.h>
#define white 1
#define gray 2
#define black 3
#define pb push_back
using namespace std;
void print();
vector<int> color;
vector<vector<int> > G;
stack<int> S;
int e,n;
void DFS_Visit(int SN)
{
color[SN] == gray ;
for(int i=0;i<G[SN].size();i++){
int a = G[SN][i];
if(color[a]== white){
DFS_Visit(a);
}
}
color[SN] = black;
S.push(SN);
}
void DFS(int SN)
{
if(color[SN]== white)
DFS_Visit(SN);
for(int i=0;i<n;i++){
if(color[i]==white)
DFS_Visit(i);
}
}
int main()
{
cout<<"Enter edges and nodes number : ";
cin>>e>>n;
color.assign(n,white);
G.assign(n,vector<int>());
int n1,n2;
cout<<"Enter edges : "<<endl;
for(int i=0;i<e;i++){
cin>>n1>>n2;
G[n1].pb(n2);
// G[n2].pb(n1);
}
DFS(0);
cout<<"Topological sorting order : ";
while(!S.empty()){
cout<<S.top()<<" ";
S.pop();
}
cout<<endl;
}