Skip to content

Commit 013a4ab

Browse files
detect_cycle_dfs.cpp
dfs,graph,easy
1 parent d6ea0bb commit 013a4ab

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include<bits/stdc++.h>
2+
#define ll long long
3+
#define pb push_back
4+
#define N 100000
5+
using namespace std;
6+
vector<ll>adj[N]; //storing the list
7+
vector<ll>vis(N);
8+
bool cycle(ll curr,ll par)
9+
{
10+
ll res=0;
11+
vis[curr]=1;
12+
for(auto neb:adj[curr])
13+
{
14+
if(neb==par)
15+
continue;
16+
if(vis[neb]==1)
17+
return 1;
18+
else
19+
res|=cycle(neb,curr);
20+
}
21+
return res;
22+
23+
}
24+
int main()
25+
{
26+
ll n,m; //no.of nodes and no. of connection
27+
cin>>n>>m;
28+
29+
for(ll i=1;i<=m;i++)
30+
{
31+
ll u,v;
32+
cin>>u>>v;
33+
adj[u].pb(v);
34+
adj[v].pb(u);
35+
36+
}
37+
for(ll i=1;i<=n;i++)
38+
vis[i]=0;
39+
ll flag=0;
40+
for(ll i=1;i<=n;i++)
41+
{
42+
if(vis[i]==0)
43+
{
44+
flag|=cycle(i,0);
45+
}
46+
}
47+
if(flag==1)
48+
cout<<"YES\n";
49+
else
50+
cout<<"NO\n";
51+
}

0 commit comments

Comments
 (0)