-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathcycleUsingBfs.cpp
More file actions
50 lines (43 loc) · 778 Bytes
/
cycleUsingBfs.cpp
File metadata and controls
50 lines (43 loc) · 778 Bytes
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
//detect cycle in graph using BFS
#include<bits/stdc++.h>
using namespace std;
bool checkCycle(int s,int n,vector<int>adj[],vector<int>& vis) {
queue<pair<int,int>> q;
vis[s]=1;
q.push({s,-1});
while(!q.empty()){
int node=q.front().first;
int par=q.front().second;
q.pop();
for(auto i:adj[node]){
if(!vis[i]){
vis[i]=1;
q.push({i,node});
}
else if(par!=i){
return true;
}
}
}
return false;
}
int main(){
int n,e;
cin>>n>>e;
vector<int>adj[n+1];
for(int i=0;i<e;i++){
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int>vis(n+1,0);
for(int i=1;i<=n;i++){
if(!vis[i]){
if(checkCycle(i,n,adj,vis)){
cout<<"true";
}
}
}
return 0;
}