-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathtopologicalSorts.cpp
64 lines (51 loc) · 1.21 KB
/
topologicalSorts.cpp
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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph {
int V;
vector<vector<int>> adj;
public:
Graph(int vertices) : V(vertices) {
adj.resize(V);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
}
void topologicalSortUtil(int v, vector<bool>& visited, stack<int>& stk) {
visited[v] = true;
for (int neighbor : adj[v]) {
if (!visited[neighbor]) {
topologicalSortUtil(neighbor, visited, stk);
}
}
stk.push(v);
}
void topologicalSort() {
vector<bool> visited(V, false);
stack<int> stk;
for (int i = 0; i < V; i++) {
if (!visited[i]) {
topologicalSortUtil(i, visited, stk);
}
}
cout << "Topological Sort: ";
while (!stk.empty()) {
cout << stk.top() << " ";
stk.pop();
}
cout << endl;
}
};
int main() {
Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Topological Sort of Graph:" << endl;
g.topologicalSort();
return 0;
}