diff --git a/Graphs/TopologicalSort.cpp b/Graphs/TopologicalSort.cpp new file mode 100644 index 0000000..a0b8688 --- /dev/null +++ b/Graphs/TopologicalSort.cpp @@ -0,0 +1,75 @@ +// Topological Sort +// O (V+E) + +#include +using namespace std; + +void init(){ + #ifndef ONLINE_JUDGE + freopen("input.txt", "r", stdin) ; + freopen("output.txt", "w", stdout) ; + #endif +} + +bool dfs(int v, vector>& graph, vector& visited, vector& recStack, stack& topologicalOrder){ + visited[v]=true; + recStack[v]=true; + for(int child: graph[v]){ + if(recStack[child]) + return false; + if(visited[child]==false){ + if(dfs(child,graph,visited,recStack,topologicalOrder)==false) + return false; + } + } + topologicalOrder.push(v); + recStack[v]=false; + return true; +} +vector findTopologicalOrder(int numCourses, vector>& graph) { + + // traverse the graph and find topological sort + stack topologicalOrder; + vector visited(numCourses);// for visited node + vector recStack(numCourses);// for rec stack to check if there is back-edge + for(int i=0;i ans; + for(int i=0;i>n>>m; + //create graph + vector> graph(n); + for(int i=0;i>a>>b; + graph[a].push_back(b); + } + vector ans=findTopologicalOrder(n,graph); + cout<<"The topological sort is as follows\n"; + for(int i:ans) + cout<