-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathTopologicalSort.cpp
More file actions
69 lines (66 loc) · 1.21 KB
/
TopologicalSort.cpp
File metadata and controls
69 lines (66 loc) · 1.21 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
//TOPOLOGICAL SORT USING BOTH BFS AND DFS.
class Solution
{
public:
//USING BFS
vector<int> topoSort(int V, vector<int> adj[])
{
vector<int> indegree(V, 0);
vector<int> ans;
for(int i=0;i<V;i++)
{
for(auto &x : adj[i])
indegree[x]++;
}
queue<int> q;
for(int i=0;i<V;i++)
{
if(indegree[i]==0)
q.push(i);
}
while(!q.empty())
{
int node = q.front();
q.pop();
ans.push_back(node);
for(auto &x : adj[node])
{
indegree[x]--;
if(indegree[x]==0)
q.push(x);
}
}
return ans;
}
/* USING DFS
void dfs(vector<int> adj[], vector<int> &viz, int &i, stack<int> &s)
{
viz[i]=1;
for(auto &x : adj[i])
{
if(!viz[x])
dfs(adj, viz, x, s);
}
s.push(i);
}
vector<int> topoSort(int V, vector<int> adj[])
{
// code here
vector<int> viz(V, 0);
vector<int> ans;
stack<int> s;
for(int i=0;i<V;i++)
{
if(!viz[i])
dfs(adj, viz, i, s);
}
while(!s.empty())
{
int node = s.top();
s.pop();
ans.push_back(node);
}
return ans;
}
*/
};