-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopological Sort.cpp
More file actions
120 lines (100 loc) · 1.67 KB
/
Topological Sort.cpp
File metadata and controls
120 lines (100 loc) · 1.67 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
Topological Sort
Time Complexity: O(M+N)
*/
#include <bits/stdc++.h>
using namespace std;
class Graph
{
private:
int V;
vector <int> *adj_list;
bool *visited_DFS;
stack <int>S;
int current_label;
int *topological_ordering;
public:
Graph(int V)
{
this->V = V;
this->adj_list = new vector<int>[V];
this->visited_DFS = new bool[V];
for(int v = 0; v<V; v++)
{
visited_DFS[v] = false;
}
this->topological_ordering = new int[V];
}
void add_edge(int u, int v)
{
adj_list[u].push_back(v);
}
void reset_DFS()
{
for(int v = 0; v<V; v++)
{
visited_DFS[v] = false;
}
}
void DFS(int s)
{
S.push(s);
while(!S.empty())
{
int temp = S.top();
S.pop();
if(visited_DFS[temp] == false)
{
visited_DFS[temp] = true;
for(int n = 0; n<adj_list[temp].size(); n++)
{
DFS(adj_list[temp][n]);
}
topological_ordering[current_label] = s;
current_label--;
}
}
}
void topological_sort()
{
reset_DFS();
current_label = V-1;
for(int i = 0; i<V; i++)
{
if(visited_DFS[i] == false)
{
DFS(i);
}
}
}
void print_topological_ordering()
{
cout<<"The topological ordering is: "<<endl;
for(int i = 0; i<V; i++)
{
cout<<topological_ordering[i];
if(i != V-1)
{
cout<<"->";
}
else
{
cout<<endl;
}
}
}
};
int main()
{
int V;
cin>>V;
Graph g(V);
int u,v;
while(cin>>u>>v)
{
g.add_edge(u,v);
}
g.topological_sort();
g.print_topological_ordering();
return 0;
}