diff --git a/TopologicalSort.cpp b/TopologicalSort.cpp index 12874d679..0d74a448c 100644 --- a/TopologicalSort.cpp +++ b/TopologicalSort.cpp @@ -1,84 +1,67 @@ -#include -#include -#include -using namespace std; - -class Graph { - int V; - - list* adj; - - - void topologicalSortUtil(int v, bool visited[], stack& Stack); - -public: - Graph(int V); - - - void addEdge(int v, int w); - - - void topologicalSort(); -}; - -Graph::Graph(int V) -{ - this->V = V; - adj = new list[V]; -} - -void Graph::addEdge(int v, int w) -{ - adj[v].push_back(w); -} - -void Graph::topologicalSortUtil(int v, bool visited[], - stack& Stack) -{ - - visited[v] = true; - - - list::iterator i; - for (i = adj[v].begin(); i != adj[v].end(); ++i) - if (!visited[*i]) - topologicalSortUtil(*i, visited, Stack); - - - Stack.push(v); -} - -void Graph::topologicalSort() -{ - stack Stack; - - - bool* visited = new bool[V]; - for (int i = 0; i < V; i++) - visited[i] = false; - - - for (int i = 0; i < V; i++) - if (visited[i] == false) - topologicalSortUtil(i, visited, Stack); - - while (Stack.empty() == false) { - cout << Stack.top() << " "; - Stack.pop(); - } -} -int main() -{ - Graph g(6); - g.addEdge(5, 2); - g.addEdge(5, 0); - g.addEdge(4, 0); - g.addEdge(4, 1); - g.addEdge(2, 3); - g.addEdge(3, 1); - - cout << "Topological Sort:"; - g.topologicalSort(); - - return 0; -} +#include + +using namespace std; + +class Solution +{ + void findTopoSort(int node, vector &vis, stack &st, vector adj[]) + { + vis[node] = 1; + + for (auto it : adj[node]) + { + if (!vis[it]) + { + findTopoSort(it, vis, st, adj); + } + } + st.push(node); + } + +public: + vector topoSort(int N, vector adj[]) + { + stack st; + vector vis(N, 0); + for (int i = 0; i < N; i++) + { + if (vis[i] == 0) + { + findTopoSort(i, vis, st, adj); + } + } + vector topo; + while (!st.empty()) + { + topo.push_back(st.top()); + st.pop(); + } + return topo; + } +}; + +int main() +{ + + int N = 6; + + vector adj[5 + 1]; + + adj[5].push_back(2); + adj[5].push_back(0); + adj[4].push_back(0); + adj[4].push_back(1); + adj[2].push_back(3); + adj[3].push_back(1); + + Solution obj; + vector res = obj.topoSort(6, adj); + + cout << "Toposort of the given graph is:" << endl; + for (int i = 0; i < res.size(); i++) + { + cout << res[i] << " "; + } + + return 0; +} \ No newline at end of file