File tree Expand file tree Collapse file tree 1 file changed +94
-0
lines changed Expand file tree Collapse file tree 1 file changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering
3
+ of vertices such that for every directed edge uv, vertex u comes before v in
4
+ the ordering. Topological Sorting for a graph is not possible if the graph is
5
+ not a DAG.
6
+ */
7
+
8
+ #include < bits/stdc++.h>
9
+ using namespace std ;
10
+
11
+ vector<vector<int >> adjList;
12
+ stack<int > s;
13
+ bool *visited;
14
+
15
+ // Number of Test Cases (Vertices)
16
+ int n;
17
+
18
+ // function to Create and represent a graph by storing data.
19
+ void createGraph ()
20
+ {
21
+ int x, y;
22
+ adjList.resize (n);
23
+
24
+ for (int j = 0 ; j < n; j++)
25
+ {
26
+ cin >> x >> y;
27
+ adjList[x].push_back (y);
28
+ }
29
+ }
30
+
31
+ // A recursive function used by topoSortFun.
32
+ void topoSortFun (int i)
33
+ {
34
+ visited[i] = true ;
35
+ for (int j = 0 ; j < adjList[i].size (); j++)
36
+ {
37
+ int key = adjList[i][j];
38
+ if (!visited[key])
39
+ topoSortFun (key);
40
+ }
41
+ s.push (i);
42
+ }
43
+
44
+ // The function to do Topological Sort. It uses recursive topoSortFun().
45
+ void topoSort ()
46
+ {
47
+ memset (visited, false , sizeof (visited));
48
+
49
+ for (int i = 0 ; i < n; i++)
50
+ {
51
+ if (!visited[i])
52
+ topoSortFun (i);
53
+ }
54
+ }
55
+
56
+ void display ()
57
+ {
58
+ for (int i = 0 ; i < n; i++)
59
+ {
60
+ cout << s.top () << " " ;
61
+ s.pop ();
62
+ }
63
+ }
64
+
65
+ int main ()
66
+ {
67
+ cout<<" Enter number of node you want to add: " ;
68
+ cin >> n;
69
+ visited = new bool [n];
70
+ cout<<" Enter nodes of graph: " ;
71
+ createGraph ();
72
+ topoSort ();
73
+ cout<<" Graph after topological sort: \n " ;
74
+ display ();
75
+ }
76
+
77
+ /*
78
+ Test Case:
79
+ Input:
80
+ Enter number of node you want to add: 6
81
+ Enter nodes of graph:
82
+ 5 2
83
+ 5 0
84
+ 4 0
85
+ 4 1
86
+ 2 3
87
+ 3 1
88
+ Output:
89
+ Graph after topological sort:
90
+ 5 4 2 3 1 0
91
+
92
+ Time Complexity: O(V + E) – where V is the number of vertices and E is the number of edges.
93
+ Space Complexity: O(V)
94
+ */
You can’t perform that action at this time.
0 commit comments