-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCycle_Detection_Undirected_graph
More file actions
53 lines (45 loc) · 1.18 KB
/
Cycle_Detection_Undirected_graph
File metadata and controls
53 lines (45 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
// Detect Cycle in Undirected Graph
// Author: Knowledge Center
// https://www.youtube.com/c/KnowledgeCenter/
// Video Explanation: https://youtu.be/Gx-uJSqIa1Q
#include <iostream>
#include <vector>
using namespace std;
class Graph{
int m_v;
vector<vector<int>> m_adj;
bool hasCycle_rec(int u, vector<bool>& visited, int parent){
visited[u] = true;
//cout << u << endl;
for(int v : m_adj[u]){
if(visited[v] && v != parent) return true;
if(!visited[v] && hasCycle_rec(v, visited, u)) return true;
}
return false;
}
public:
Graph(int v):m_v(v), m_adj(v){}
void add_Edge(int u, int v){
m_adj[u].push_back(v);
m_adj[v].push_back(u);
}
bool hasCycle(){
vector<bool> visited(m_v, false);
for(int i = 0; i < m_v; ++i){
if(!visited[i] && hasCycle_rec(i, visited, -1)) return true;
}
return false;
}
};
int main(){
Graph G(5);
G.add_Edge(0,1);
G.add_Edge(0,3);
//G.add_Edge(0,4);
G.add_Edge(1,2);
G.add_Edge(3,4);
//G.add_Edge(2,4);
bool cycle = G.hasCycle();
cout << boolalpha << cycle << endl;
return 0;
}