-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopological sort.cpp
More file actions
38 lines (35 loc) · 864 Bytes
/
Topological sort.cpp
File metadata and controls
38 lines (35 loc) · 864 Bytes
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
/*
Problem Link: https://practice.geeksforgeeks.org/problems/topological-sort/1
*/
class Solution
{
private:
void dfs(int node, vector<int> &vis, vector<int> adj[], stack<int> &st){
vis[node]=1;
for(auto adjNode: adj[node]){
if(!vis[adjNode]){
dfs(adjNode, vis, adj, st);
}
}
st.push(node);
}
public:
//Function to return list containing vertices in Topological order.
vector<int> topoSort(int V, vector<int> adj[])
{
// DFS code here
stack<int> st;
vector<int> ans;
vector<int> vis(V, 0);
for(int i=0; i<V; i++){
if(!vis[i]){
dfs(i, vis, adj, st);
}
}
while(!st.empty()){
ans.push_back(st.top());
st.pop();
}
return ans;
}
};