File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-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
+ cout << " Enter the number of vertices and the number of directed edges\n " ;
31
+ cin >> n >> m;
32
+ int x , y;
33
+ G.resize (n , vector<int >());
34
+ for (int i = 0 ; i < n ; ++i) {
35
+ cin >> x >> y;
36
+ x-- , y--; // to convert 1-indexed to 0-indexed
37
+ G[x].push_back (y);
38
+ }
39
+ topological_sort ();
40
+ cout << " Topological Order : \n " ;
41
+ for (int v : ans) {
42
+ cout << v + 1 << ' ' ; // converting zero based indexing back to one based.
43
+ }
44
+ cout << ' \n ' ;
45
+ return 0 ;
46
+ }
You can’t perform that action at this time.
0 commit comments