Cycle detection in graph using DFS | Graph Theory
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define endl "\n"
vector<ll> arr[1000009];
ll vis[1000009],color[1000009];
bool dfs(ll v,ll par)
{
vis[v]=1;
for(auto child :arr[v])
{
if(vis[child]==0)
{
bool r1;
if(dfs(child,v)==true)return true;
}
else{
if(child!=par)return true;
}
}
return false;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll node ,edge;
cin>>node>>edge;
while(edge--)
{
ll x,y;
cin>>x>>y;
arr[x].push_back(y);
arr[y].push_back(x);
}
bool r;
r=dfs(1,-1);
if(r==true)cout<<"Yes\n";
else cout<<"No\n";
return 0;
}
0 Comments