fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> adj_list[100];
  5. int visited[100];
  6.  
  7. bool DFS(int currnode, int par) {
  8. visited[currnode] = 1;
  9.  
  10. for (int i = 0; i < adj_list[currnode].size(); i++) {
  11. int child = adj_list[currnode][i];
  12. if (!visited[child]) {
  13. if (DFS(child, currnode)) {
  14. return true; // Cycle found in recursion
  15. }
  16. } else if (child != par) {
  17. return true; // Found a back edge → cycle
  18. }
  19. }
  20.  
  21. return false; // No cycle in this path
  22. }
  23.  
  24. int main() {
  25. int node, edge;
  26. cin >> node >> edge;
  27.  
  28. for (int i = 0; i < edge; i++) {
  29. int u, v;
  30. cin >> u >> v;
  31. adj_list[u].push_back(v);
  32. adj_list[v].push_back(u);
  33. }
  34.  
  35. bool foundCycle = false;
  36.  
  37. for (int i = 1; i <= node; i++) {
  38. if (!visited[i]) {
  39. if (DFS(i, -1)) {
  40. foundCycle = true;
  41. break;
  42. }
  43. }
  44. }
  45.  
  46. if (foundCycle)
  47. cout << "Cycle detected" << endl;
  48. else
  49. cout << "No cycle detected" << endl;
  50.  
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0.01s 5288KB
stdin
4 4
1 2
2 3
3 4
4 2
stdout
Cycle detected