-
Notifications
You must be signed in to change notification settings - Fork 77
/
Detect_cycle_in_a_directed_graph_using_DFS.cpp
82 lines (57 loc) · 1.39 KB
/
Detect_cycle_in_a_directed_graph_using_DFS.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
81
82
// Problem Statement: Given a directed graph with V vertices and E edges, check whether it contains any cycle or not.
// Example 1:
// Input: N = 10, E = 11
// Output: true
// Explanation: 8->9->10 is a cycle.
// Example 2:
// Input Format: N = 10, E = 10
// Result: false
// Explanation: No cycle detected.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
bool dfsCheck(int node, vector<int> adj[], int vis[], int pathVis[]) {
vis[node] = 1;
pathVis[node] = 1;
// traverse for adjacent nodes
for (auto it : adj[node]) {
// when the node is not visited
if (!vis[it]) {
if (dfsCheck(it, adj, vis, pathVis) == true)
return true;
}
// if the node has been previously visited
// but it has to be visited on the same path
else if (pathVis[it]) {
return true;
}
}
pathVis[node] = 0;
return false;
}
public:
// Function to detect cycle in a directed graph.
bool isCyclic(int V, vector<int> adj[]) {
int vis[V] = {0};
int pathVis[V] = {0};
for (int i = 0; i < V; i++) {
if (!vis[i]) {
if (dfsCheck(i, adj, vis, pathVis) == true) return true;
}
}
return false;
}
};
int main() {
// V = 11, E = 11;
vector<int> adj[11] = {{}, {2}, {3}, {4, 7}, {5}, {6}, {}, {5}, {9}, {10}, {8}};
int V = 11;
Solution obj;
bool ans = obj.isCyclic(V, adj);
if (ans)
cout << "True\n";
else
cout << "False\n";
return 0;
}