-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCycleBFS.cpp
More file actions
62 lines (54 loc) · 1.18 KB
/
CycleBFS.cpp
File metadata and controls
62 lines (54 loc) · 1.18 KB
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
57
58
59
60
61
62
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
bool check_cycle(int node,map<int,set<int>> adj,map<int,bool> visit, map<int,int> parent){
visit[node]=1;
parent[node]=-1;
queue<int> q;
q.push(node);
while(!q.empty()){
int frontnode = q.front();
q.pop();
for(auto it: adj[frontnode]){
if(!visit[it]){
q.push(it);
visit[it]=1;
parent[it]=frontnode;
}
else if(visit[it]==1 && parent[frontnode]!= it){
return true;
}
}
}
return false;
}
void BFS(int v, map<int,set<int>> adj){
map<int,bool> visit;
map<int,int> parent;
int flag=0;
for(int i=0;i<v;i++){
if(!visit[i]){
if(check_cycle(i,adj,visit,parent)){
cout<<"true";
flag=1;
break;
}
}
}
if(flag==0){
cout<<"false";
}
}
int main(){
int n,m;
cin>>n>>m;
map<int, set<int>> adj;
for(int i=0;i<m;i++){
int u,v;
cin>>u>>v;
adj[u].insert(v);
adj[v].insert(u);
}
BFS(n, adj);
return 0;
}