-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle_detect_dfs.cpp
56 lines (51 loc) · 1.02 KB
/
cycle_detect_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
56
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
vector<int> graph[N];
bool cycle=false;
int vis[N];
void dfs(int cur, int par)
{
cout << cur << '\n';
vis[cur] = 1;
for (auto x : graph[cur]) // x=child node
{
if (!vis[x])
{
dfs(x, cur);
}
else if (x != par) // it is visited and not equal to parent
{
// backedge
//cout << cur << " " << x << endl;
cycle=true;
}
}
}
int main()
{
int v, e;
cin >> v >> e;
for (int i = 0; i < e; i++)
{
int x, y;
cin >> x >> y;
// undirected
graph[x].push_back(y);
graph[y].push_back(x);
}
for (int i = 1; i <= v; i++)
{
if (!vis[i])
{
dfs(i, 0); // o can't be parents of any node
}
}
if(cycle){
cout<<"Yes Cycle Found"<<endl;
}
else{
cout<<"No Cycle Found"<<endl;
}
return 0;
}