-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCycle_detection_dfs.cpp
55 lines (49 loc) · 1.03 KB
/
Cycle_detection_dfs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<bits/stdc++.h>
using namespace std;
//Detect cycle in unidirected graph using DFS
int n,m;
vector<vector<int>>graph;
vector<int>color;
vector<int>parent;
int start_cycle, end_cycle;
bool dfs(int v, int par){
color[v] = 1;
for(int u: graph[v]){
if(color[u] == 0){
parent[u] = v;
if(dfs(u, parent[u]))
return true;
}
else if(color[u] == 1){
start_cycle = u;
end_cycle = u;
return true;
}
}
color[v] =2;
return false;
}
void is_cycle(){
color.assign(n+1, 0);
parent.assign(n+1, -1);
start_cycle = -1;
for(int u=1;u<=n;u++){
if(color[u] == 0 && dfs(u, parent[u]))
break;
}
if(start_cycle == -1)
cout<<"No cycle found\n";
else
cout<<"Cycle found\n";
}
signed main(){
cin>>n>>m;
graph.resize(n+1);
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
graph[u].push_back(v);
graph[v].push_back(u);
}
is_cycle();
}