From 1a0478145579fff65b051de91bf2fdabaedd37df Mon Sep 17 00:00:00 2001 From: harshil0802 <86008142+harshil0802@users.noreply.github.com> Date: Tue, 18 Oct 2022 00:03:51 +0530 Subject: [PATCH] Create Topological_sort.cpp --- Topological_sort.cpp | 86 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Topological_sort.cpp diff --git a/Topological_sort.cpp b/Topological_sort.cpp new file mode 100644 index 0000000..8d13f4b --- /dev/null +++ b/Topological_sort.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; + + // } Driver Code Ends +class Solution +{ + public: + //Function to return list containing vertices in Topological order. + vector topoSort(int V, vector adj[]) + { + vector indegree(V,0); + for(int i=0; i qu; + for(int i=0; i topo; + while(!qu.empty()){ + int node=qu.front(); + qu.pop(); + topo.push_back(node); + for(int j=0; j &res, vector adj[]) { + + if(V!=res.size()) + return 0; + + vector map(V, -1); + for (int i = 0; i < V; i++) { + map[res[i]] = i; + } + for (int i = 0; i < V; i++) { + for (int v : adj[i]) { + if (map[i] > map[v]) return 0; + } + } + return 1; +} + +int main() { + int T; + cin >> T; + while (T--) { + int N, E; + cin >> E >> N; + int u, v; + + vector adj[N]; + + for (int i = 0; i < E; i++) { + cin >> u >> v; + adj[u].push_back(v); + } + + Solution obj; + vector res = obj.topoSort(N, adj); + + cout << check(N, res, adj) << endl; + } + + return 0; +}