-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopologicalSort.cpp
More file actions
86 lines (79 loc) · 1.76 KB
/
Copy pathtopologicalSort.cpp
File metadata and controls
86 lines (79 loc) · 1.76 KB
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
80
81
82
83
84
85
86
#include <bits/stdc++.h>
using namespace std;
#include <bits/stdc++.h>
using namespace std;
void dfs(int node, vector<int> adj[], vector<bool> &visited, vector<int> &stk)
{
visited[node] = true;
for (auto it : adj[node])
if (!visited[it])
dfs(it, adj, visited, stk);
stk.push_back(node);
}
vector<int> topoSortByDFS(int V, vector<int> adj[])
{
// code here
vector<bool> visited(V, false);
vector<int> stk;
for (int i = 0; i < V; i++)
{
if (!visited[i])
dfs(i, adj, visited, stk);
}
reverse(stk.begin(), stk.end());
return stk;
}
vector<int> KAHNsAlgo(int V, vector<int> adj[])
{
// code here
vector<int> inDegree(V, 0);
// find InDegree
for (int i = 0; i < V; i++)
for (auto it : adj[i])
inDegree[it]++;
queue<int> q;
// start of topo sort
for (int i = 0; i < V; i++)
if (inDegree[i] == 0)
q.push(i);
vector<int> ans;
// simple bfs
while (!q.empty())
{
int node = q.front();
ans.push_back(node);
q.pop();
for (auto it : adj[node])
{
inDegree[it]--;
if (inDegree[it] == 0)
q.push(it);
}
}
return ans;
}
int main()
{
int V, E;
cout << "Enter number of vertices and edges: " << endl;
cin >> V >> E;
vector<int> adj[V];
cout << "please enter as: u -> v :\n";
for (int i = 0; i < E; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
vector<int> ans = topoSortByDFS(V, adj);
if (ans.size() != V)
cout << "NIL";
else
{
cout << "Topological Sort :-\n";
for (int a : ans)
cout << " " << a;
}
cout << endl;
return 0;
}