-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topological Sort.cpp
87 lines (66 loc) · 1.32 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
void dfs(int i,stack<int>& s,vector<int> adj[],vector<int>& vis)
{
vis[i]=true;
for(int v:adj[i])
{
if(!vis[v])
dfs(v,s,adj,vis);
}
s.push(i);
}
int* topoSort(int V, vector<int> adj[]) { //dependency //Only possible for DAG
stack<int> s;
vector<int> vis(V,false);
for(int i=0;i<V;i++)
{
if(!vis[i])
dfs(i,s,adj,vis);
}
int *a;
a=new int[s.size()];
int j=0;
while(!s.empty())
{
a[j]=s.top();
j++;
s.pop();
}
return a;
}
## kahns algorithm
int* topoSort(int V, vector<int> adj[]) {
vector<bool> vis(V,false);
vector<int> indegree(V,0);
int i,count=0;
for(i=0;i<V;i++)
{
for(int v:adj[i])
{
indegree[v]++;
}
}
queue<int> q;
for(i=0;i<V;i++)
{
if(indegree[i]==0)
q.push(i);
}
int *a;
a=new int[V];
int j=0;
while(!q.empty())
{
int k=q.front();
q.pop();
a[j]=k;
j++;
for(int v:adj[k])
{
indegree[v]--;
if(indegree[v]==0)
q.push(v);
}
count++; //if count!=V then there is cycle
}
return a;
}