diff --git a/Graph-Theory/topological sort/topological_sort.cpp b/Graph-Theory/topological sort/topological_sort.cpp new file mode 100644 index 0000000..165d517 --- /dev/null +++ b/Graph-Theory/topological sort/topological_sort.cpp @@ -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(vectoradj[], int u, bool visited[], stack&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 topoSort(int V, vector adj[]) { + // Your code here + bool *visited = new bool[V]; + stackst; + 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); + } + } + vectorans; + while(st.size()) { + int a = st.top(); + ans.push_back(a); + st.pop(); + } + return ans; +}