-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cycle-Exists-or-not.cpp
58 lines (50 loc) · 1.39 KB
/
Cycle-Exists-or-not.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
//
// Created by rajat joshi on 17-06-2021.
//
#include<iostream>
#include<set>
#define NODE 5
using namespace std;
int graph[NODE][NODE] =
{{0, 1, 1, 0,0},
{1, 0, 1, 1,1},
{1, 1, 0, 1,0},
{0, 1, 1, 0,1},
{0, 1, 0, 1,0}
};
bool dfs(int curr, set<int>&wSet, set<int>&gSet, set<int>&bSet) {
wSet.erase(wSet.find(curr));
gSet.insert(curr);
for(int v = 0; v < NODE; v++) {
if(graph[curr][v] != 0) {
if(bSet.find(v) != bSet.end())
continue; if(gSet.find(v)
!= gSet.end()) return true;
if(dfs(v, wSet, gSet, bSet))
return true;
}
}
gSet.erase(gSet.find(curr));
bSet.insert(curr); return
false;
}
bool hasCycle() { set<int>
wSet, gSet, bSet; for(int
i = 0; i<NODE; i++)
wSet.insert(i);
while(wSet.size() > 0) { for(int current = 0; current < NODE; current++) {
if(wSet.find(current) != wSet.end())
if(dfs(current, wSet, gSet, bSet)) return
true;
}
}
return false;
}
int main() {
bool res;
res =hasCycle();
if(res)
cout << "The graph has a cycle." << endl;
else
cout << "The graph has no cycle." << endl;
}