Skip to content

Instantly share code, notes, and snippets.

@Antardas
Last active January 9, 2023 18:46
Show Gist options
  • Save Antardas/ace2ff05c9faad295e14920946812de9 to your computer and use it in GitHub Desktop.
Save Antardas/ace2ff05c9faad295e14920946812de9 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int>adj_list[N];
int visited[N], inDegree[N];
int n, m;
bool detect_cycle(int node) {
queue<int>q;
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
int count = 0;
while (!q.empty())
{
int u = q.front();
q.pop();
count++;
for (int i = 0; i < adj_list[u].size(); i++) {
int v = adj_list[u][i];
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
}
}
}
if (count != n) {
return true;
}
else {
return false;
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj_list[u].push_back(v);
inDegree[v]++;
}
bool got_cycle = detect_cycle(1);
if (got_cycle) {
cout << "Cycle Exist" << endl;
}
else {
cout << "Cycle doesn't exist" << endl;
}
}
/*
Input:
4 5
1 3
1 2
2 3
3 4
4 2
---------
4 4
1 2
1 3
2 4
3 4
---------
5 4
1 2
2 4
4 3
3 5
5 4
*/
@Antardas
Copy link
Author

Antardas commented Jan 9, 2023

This Code I have write with the help of this video: https://youtu.be/G1HuCjgvJb0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment