File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+ #include < algorithm>
4
+ using namespace std ;
5
+
6
+ int n , m; // For number of Vertices (V) and number of edges (E)
7
+ vector< vector<int > > G;
8
+ vector<bool > visited;
9
+ vector<int > ans;
10
+
11
+ void dfs (int v) {
12
+ visited[v] = true ;
13
+ for (int u : G[v]) {
14
+ if (!visited[u])
15
+ dfs (u);
16
+ }
17
+ ans.push_back (v);
18
+ }
19
+
20
+ void topological_sort () {
21
+ visited.assign (n, false );
22
+ ans.clear ();
23
+ for (int i = 0 ; i < n; ++i) {
24
+ if (!visited[i])
25
+ dfs (i);
26
+ }
27
+ reverse (ans.begin (), ans.end ());
28
+ }
29
+ int main (){
30
+ cin >> n >> m;
31
+ int x , y;
32
+ G.resize (n , vector<int >());
33
+ for (int i = 0 ; i < n ; ++i) {
34
+ cin >> x >> y;
35
+ x-- , y--; // to convert 1-indexed to 0-indexed
36
+ G[x].push_back (y);
37
+ }
38
+ topological_sort ();
39
+ cout << " Topological Order : \n " ;
40
+ for (int v : ans) {
41
+ cout << v << ' ' ;
42
+ }
43
+ cout << ' \n ' ;
44
+ return 0 ;
45
+ }
You can’t perform that action at this time.
0 commit comments