-
Notifications
You must be signed in to change notification settings - Fork 0
/
UndirectedCycleDetection.cpp
70 lines (67 loc) · 1.34 KB
/
UndirectedCycleDetection.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
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class Graph
{
private:
list<int> *l; // yeh bani h lists of lists
int V;
public:
Graph(int V)
{
this->V = V;
l = new list<int>[V];
}
void addEdge(int x, int y)
{
l[x].push_back(y);
l[y].push_back(x);
}
bool cycle_detect_helper(int node, bool *visited, int parent)
{
visited[node] = true;
for (auto nbr : l[node])
{
if (!visited[nbr])
{
bool cycle_mila = cycle_detect_helper(nbr, visited, node);
if (cycle_mila)
{
return true;
}
}
else if (nbr != parent)
{
return true;
}
}
return false;
}
bool cycle_detect()
{
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
{
visited[i] = false;
}
return cycle_detect_helper(0, visited, -1);
}
};
int main(int argc, char const *argv[])
{
Graph<int> g(5);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
// g.addEdge(4, 0);
if (g.cycle_detect())
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
return 0;
}