Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Graph-Theory/topological sort/topological_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// The Graph structure is as folows

/* Function which sorts the graph vertices in topological form
* N: number of vertices
* adj[]: input graph
*/

void topological(vector<int>adj[], int u, bool visited[], stack<int>&st) {
if(visited[u] == false) {
visited[u] = true;
for(auto e : adj[u]) {
if(!visited[e]) {
topological(adj, e ,visited, st);
}
}
}
st.push(u);
}
vector<int> topoSort(int V, vector<int> adj[]) {
// Your code here
bool *visited = new bool[V];
stack<int>st;
for(int i = 0; i < V; i++) {
visited[i] = false;
}
for(int i = 0; i < V; i++) {
if(visited[i] == false) {
topological(adj, i , visited, st);
}
}
vector<int>ans;
while(st.size()) {
int a = st.top();
ans.push_back(a);
st.pop();
}
return ans;
}