-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathGraphs_cycle_detection_bfs.cpp
67 lines (64 loc) · 1.73 KB
/
Graphs_cycle_detection_bfs.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
57
58
59
60
61
62
63
64
65
66
67
// Graphs Cycle detection using BFS
// Program Author : Abhisek Kumar Gupta
#include<bits/stdc++.h>
using namespace std;
template<typename T>
class Graph{
map<T, list<T> > L;
public:
Graph(){
}
void add_edge(T u, T v, bool bidir = true){
L[u].push_back(v);
if(bidir){
L[v].push_back(u);
}
}
void print_edge(){
for(auto x : L){
cout << x.first << "->";
for(auto element : x.second){
cout << element << ",";
}
cout << endl;
}
}
bool is_cyclic(T source){
map<T, bool> visited;
map<T, int> parent;
queue<T> q;
q.push(source);
visited[source] = true;
parent[source] = source;
while(!q.empty()){
T node = q.front();
q.pop();
for(T neighbour : L[node]){
if(visited[neighbour]==true && parent[node] != neighbour){
return true;
}
else if(!visited[neighbour]){
visited[neighbour] = true;
q.push(neighbour);
parent[neighbour] = node;
}
}
}
return false;
}
};
int main(){
Graph<int> g;
g.add_edge(1,2);
g.add_edge(1,4);
g.add_edge(4,3);
g.add_edge(2,3);
g.print_edge();
if(g.is_cyclic(1)){
cout << "Graph is Cyclic";
}
else{
cout << "Graph is not Cyclic";
}
return 0;
}