-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbfs_cycle_detection.cpp
96 lines (69 loc) · 1.92 KB
/
bfs_cycle_detection.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mp make_pair
#define pb push_back
class Graph{
map<int, list<int> > adjList;
public:
void addEdge(int u, int v){
adjList[u].pb(v);
adjList[v].pb(u);
}
bool bfs_cycle_detection(int src){
queue<int> q;
map<int,bool> visited;
map<int, int> parent;
q.push(src);
parent[src] = src;
visited[src] = true;
while(!q.empty()){
int T = q.front();
q.pop();
for(auto i: adjList[T]){
if(visited[i]==true and i!=parent[T]){ //
return true;
}
if(!visited[i]){
visited[i] = true;
parent[i] = T;
q.push(i);
}
}
}
return false;
}
bool isCyclicHelper(int node, map<int, bool> &visited, map<int, bool> &inStack){
visited[node] = true;
inStack[node] = true;
// Explore the neighbours of the node
for(int neigh: adjList[node]){
// cuur node is not visited and the forward cycle returns true
if(!visited[neigh] && (isCyclicHelper(neigh,visited, inStack)||inStack[neigh])){
return true;
}
// Going to pop out the node
inStack[neigh] = false;
return false;
}
}
bool dfsIsCyclic(){
map<int,bool> visited;
map<int,bool> inStack;
// To check for cycle in each dfs tree
for(auto i:adjList){
int node = i.first;
if(!visited[node]){
bool cyclePresent = isCyclicHelper(node,visited, inStack);
if(cyclePresent) {
return true;
}
}
}
return false;
}
};
int main() {
return 0;
}