-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCycle_Detection_Directed_Graph
More file actions
60 lines (51 loc) · 1.28 KB
/
Cycle_Detection_Directed_Graph
File metadata and controls
60 lines (51 loc) · 1.28 KB
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
// Detect Cycle in Directed Graph
// Author: Knowledge Center
// https://www.youtube.com/c/KnowledgeCenter/
// Video Explanation: https://youtu.be/1CdgY5KTQQE
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
enum node_states_en{
UNVISITED,
INSTACK,
VISITED
};
class Graph{
int m_v;
vector<vector<int>> m_adj;
int time;
bool DFS_rec(int s, vector<node_states_en>& visited){
visited[s] = INSTACK;
//cout << s << endl;
for(int u: m_adj[s]){
if(visited[u] == INSTACK) return true;
if(visited[u] == UNVISITED && DFS_rec(u, visited)) return true;
}
visited[s] = VISITED;
return false;
}
public:
Graph(int v):m_v(v), m_adj(v), time(0){}
void addEdge(int u, int v){
m_adj[u].push_back(v);
}
bool hasCycle(){
vector<node_states_en> visited(m_v, UNVISITED);
for(int i = 0; i < m_v; ++i)
if(visited[i] == UNVISITED && DFS_rec(i, visited)) return true;
return false;
}
};
int main(){
Graph G(5);
G.addEdge(0,1);
G.addEdge(0,3);
G.addEdge(1,2);
G.addEdge(3,4);
G.addEdge(4,0);
G.addEdge(4,2);
bool hasCycle = G.hasCycle();
cout << std::boolalpha << hasCycle << endl;
return 0;
}