forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topological_sorting.cpp
79 lines (64 loc) · 1.38 KB
/
Topological_sorting.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph {
int V; // Number of vertices
vector<vector<int>> adj;
public:
Graph(int V);
void addEdge(int u, int v);
vector<int> topologicalSort();
};
Graph::Graph(int V) {
this->V = V;
adj.resize(V);
}
void Graph::addEdge(int u, int v) {
adj[u].push_back(v);
}
vector<int> Graph::topologicalSort() {
vector<int> inDegree(V, 0);
// Calculate in-degrees for all vertices
for (int u = 0; u < V; u++) {
for (int v : adj[u]) {
inDegree[v]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
vector<int> result;
while (!q.empty()) {
int u = q.front();
q.pop();
result.push_back(u);
for (int v : adj[u]) {
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
}
}
}
return result;
}
int main() {
int V = 6; // Number of vertices
Graph g(V);
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 Order: ";
vector<int> result = g.topologicalSort();
for (int vertex : result) {
cout << vertex << " ";
}
cout << endl;
return 0;
}