Skip to content

Commit

Permalink
Create TopologicalSort.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored May 30, 2024
1 parent c4b0437 commit 7978ec6
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Graphs/TopologicalSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution
{
private:
void dfs(int node,int vis[],stack<int>&s,vector<int> adj[]){
vis[node]=1;
for(auto i:adj[node]){
if(!vis[i]){
dfs(i,vis,s,adj);
}
}
s.push(node);
}
public:
//Function to return list containing vertices in Topological order.
vector<int> topoSort(int V, vector<int> adj[])
{
// code here
int vis[V]={0};
stack<int>s;
for(int i=0;i<V;i++){
if(!vis[i]){
dfs(i,vis,s,adj);
}
}
vector<int>ans;
while(!s.empty()){
ans.push_back(s.top());
s.pop();
}
return ans;
}
};

0 comments on commit 7978ec6

Please sign in to comment.