forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topological_Sort.cpp
72 lines (60 loc) · 1.48 KB
/
Topological_Sort.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
#include<bits/stdc++.h>
using namespace std;
// Function to perform topological sort
vector<int> topoSort(int V, vector<int> adj[])
{
// Initialize an array to store the in-degrees of each node
vector<int> indegree(V, 0);
// Calculate the in-degrees for each node
for(int i = 0; i < V; i++)
{
for(auto x: adj[i])
{
indegree[x]++;
}
}
// Initialize a queue to perform BFS
queue<int> q;
// Add nodes with in-degree 0 to the queue
for(int i = 0; i < V; i++)
{
if(indegree[i] == 0)
{
q.push(i);
}
}
// Initialize a vector to store the topological order
vector<int> topo;
// Perform BFS
while(!q.empty())
{
int node = q.front();
q.pop();
topo.push_back(node);
// Reduce the in-degree of adjacent nodes and add them to the queue if in-degree becomes 0
for(auto x: adj[node])
{
indegree[x]--;
if(indegree[x] == 0)
{
q.push(x);
}
}
}
return topo;
}
int main() {
int N1 = 5; // Number of nodes
vector<int> adj1[N1] = {{1, 2}, {3}, {3, 4}, {}, {}};
vector<int> res1 = topoSort(N1, adj1);
// Print the topological order
cout << "Topological Order : ";
for(int i = 0; i < res1.size(); i++)
{
cout << res1[i] << " ";
}
cout << endl;
return 0;
}
// Time Complexity: O(V+E)
// Space Complexity: O(V)