forked from Aadi71/Data-Structures-and-Algorithms-with-Aadi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle-detection-in-undirected-graph.cpp
45 lines (36 loc) · 1.08 KB
/
cycle-detection-in-undirected-graph.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
// https://www.codingninjas.com/codestudio/problems/cycle-detection-in-undirected-graph_1062670?
// BFS
#include <bits/stdc++.h>
bool isCyclicBFS(int src, unordered_map<int, bool> &visited, unordered_map<int, vector<int>> &adj){
unordered_map<int, int> parent;
parent[src] = -1;
visited[src] = 1;
queue<int>q;
q.push(src);
while(!q.empty()){
int f = q.front();
q.pop();
for(auto x: adj[f]){
if(visited[x] == true && x != parent[f]) return true;
else if(!visited[x]){
q.push(x);
visited[x] = 1;
parent[x] = f;
}
}
}
return false;
}
// DFS
bool isCyclicDFS(int node, int parent, unordered_map<int, bool> &visited, unordered_map<int, vector<int>> &adj){
visited[node] = true;
for(auto x: adj[node]){
if(!visited[x]){
bool cycleDetected = isCyclicDFS(x, node, visited, adj);
if(cycleDetected) return true;
}
else if(x != parent) return true;
}
return false;
}
// Main Solution