diff --git a/Cycle Detection in undirected graphs using BFS b/Cycle Detection in undirected graphs using BFS new file mode 100644 index 00000000..9f0c46d3 --- /dev/null +++ b/Cycle Detection in undirected graphs using BFS @@ -0,0 +1,101 @@ +#include +#include +#include + +bool isCyclicBFS(int src,unordered_map&visited, +unorderd_map >&adj, unordered_map parent) +{ + parent[src] = -1; + visited[src] = 1; + queue q; + q.push(src); + + while(!q.empty) { + int front = q.front(); + q.pop(); + + for(auto neighbour: adj[front]) { + if(visited[neighbour] == true && neighbour != parent[front]) + { + return true; + } + else if(!visited[neigbour]) + { + q.push(neighbour); + visited[neibhour] = 1; + parent[neighbour] = front; + } + } + } + return false; +} + + + +string cycleDetection (vector& edges, int n, int m) { + //create adjacency list + unorderd_map >adj; + for(int i=0; i&visited, +unoredered_map >&adj){ + visited[node] = true; + + for(auto neighbour: adj[node]) { + if(!visited[neighbour]) { + + bool cycleDetected = isCyclicDFS(neihbour, node, visited, adj);//rec call + if(cycleDetected) + return true; + } + else if(neighbour!=parent) { + //cycle present + return true; + } +} +return false; +} + + +string cycleDetection (vector& edges, int n, int m) { + //create adjacency list + unorderd_map >adj; + for(int i=0; i