-
Notifications
You must be signed in to change notification settings - Fork 0
/
DirectedCycleDetection.cpp
80 lines (77 loc) · 1.66 KB
/
DirectedCycleDetection.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
#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, bool directed = true)
{
l[x].push_back(y);
if (!directed)
{
l[y].push_back(x);
}
}
bool cycle_detect_helper(int node, bool *visited, vector<bool> &stackjesa)
{
visited[node] = true;
stackjesa[node] = true;
for (auto nbr : l[node])
{
if (stackjesa[nbr] == true)
{
return true;
}
else if (visited[nbr] == false)
{
bool cycle_mila = cycle_detect_helper(nbr, visited, stackjesa);
if (cycle_mila == true)
{
return true;
}
}
}
stackjesa[node] = false;
return false;
}
bool cycle_detect()
{
bool *visited = new bool[V];
vector<bool> stackjesa(V);
for (int i = 0; i < V; i++)
{
visited[i] = false;
stackjesa[i] = false;
}
return cycle_detect_helper(0, visited, stackjesa);
}
};
int main(int argc, char const *argv[])
{
Graph<int> g(7);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);
g.addEdge(1, 5);
g.addEdge(5, 6);
g.addEdge(4, 2); // backedge
if (g.cycle_detect())
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
return 0;
}