Skip to content

Commit 21ffc54

Browse files
committed
Cycle Detection
1 parent 8058d76 commit 21ffc54

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Graph/detectCycle.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
class Graph {
4+
5+
int v;
6+
list<int> *l;
7+
public:
8+
Graph(int v) {
9+
this->v = v;
10+
l = new list<int>[v];
11+
}
12+
void addEdge(int x, int y) {
13+
l[x].push_back(y);
14+
}
15+
16+
bool cycle_helper(int src, bool *visited, bool *stack) {
17+
visited[src] = true;
18+
stack[src] = true;
19+
20+
for (auto nbr : l[src]) {
21+
if (stack[nbr] == true) {
22+
return true;
23+
} else if (!visited[nbr]) {
24+
bool found = cycle_helper(nbr, visited, stack);
25+
if (found) {
26+
return true;
27+
}
28+
}
29+
}
30+
stack[src] = false;
31+
return false;
32+
}
33+
bool dfs() {
34+
bool *visited = new bool[v];
35+
bool *stack = new bool[v];
36+
37+
for (int i = 0; i < v; i++) {
38+
visited[i] = stack[i] = false;
39+
}
40+
41+
return cycle_helper(0, visited, stack);
42+
}
43+
};
44+
int main() {
45+
46+
Graph g(7);
47+
g.addEdge(0, 1);
48+
g.addEdge(1, 2);
49+
g.addEdge(2, 3);
50+
g.addEdge(3, 4);
51+
g.addEdge(4, 5);
52+
g.addEdge(1, 5);
53+
g.addEdge(5, 6);
54+
//g.addEdge(4,2);
55+
56+
if (g.dfs()) {
57+
cout << "Yes" << endl;
58+
} else {
59+
cout << "No" << endl;
60+
}
61+
return 0;
62+
}

0 commit comments

Comments
 (0)