Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created CycleDetection.cpp #669

Merged
merged 1 commit into from
Oct 11, 2021
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Detecting cycle in the Directed Graph using BFS



#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
bool isCyclic(int N, vector<int> adj[]) {
queue<int> q;
vector<int> indegree(N, 0);
for(int i = 0;i<N;i++) {
for(auto it: adj[i]) {
indegree[it]++;
}
}

for(int i = 0;i<N;i++) {
if(indegree[i] == 0) {
q.push(i);
}
}
int cnt = 0;
while(!q.empty()) {
int node = q.front();
q.pop();
cnt++;
for(auto it : adj[node]) {
indegree[it]--;
if(indegree[it] == 0) {
q.push(it);
}
}
}
if(cnt == N) return false;
return true;
}
};



int main()
{

int t;
cin >> t;
while(t--)
{
int V, E;
cin >> V >> E;

vector<int> adj[V];

for(int i = 0; i < E; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}

Solution obj;
cout << obj.isCyclic(V, adj) << "\n";
}

return 0;
}