-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathdetect_cycle_directed_graph.cpp
More file actions
102 lines (88 loc) · 2.71 KB
/
detect_cycle_directed_graph.cpp
File metadata and controls
102 lines (88 loc) · 2.71 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// A C++ Program to detect cycle in a graph
#include <iostream>
#include <vector>
// A directed graph G is acyclic if and only if
// a depth first search of G yields no back edges
class Graph
{
using graph = std::vector<std::vector<int>>;
int V; // No. of vertices
graph g; // two dimensional vector to represent the graph
bool isCyclicUtil(int v, std::vector<bool>& visited, std::vector<bool>& rs); // used by isCyclic()
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // to add an edge to graph
bool isCyclic(); // returns true if there is a cycle in this graph
};
Graph::Graph(int V)
{
this->V = V;
g = std::move(graph(V,std::vector<int>()));
}
void Graph::addEdge(int v, int w)
{
g[v].push_back(w); // add v and w to graph
}
bool Graph::isCyclicUtil(int v, std::vector<bool>& visited, std::vector<bool>& recStack)
{
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
for(auto s : g[v])
{
if(visited[s] == false)
{
if (isCyclicUtil(s, visited, recStack))
return true;
}
else if (recStack[s]) // If visited[s] is TRUE then check only recursionStack
return true;
}
recStack[v] = false; // remove the vertex from recursion stack
return false;
}
// Returns true if the graph contains a cycle, else false.
bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
std::vector<bool> visited(V,false);
std::vector<bool> recStack(V,false);
// Call the recursive helper function to detect cycle in different
// DFS trees
for(int i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack))
return true;
return false;
}
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
if(g.isCyclic())
std::cout << "Graph contains cycle"<<std::endl;
else
std::cout << "Graph doesn't contain cycle"<<std::endl;
Graph g2(9);
g2.addEdge(0,1);
g2.addEdge(1,2);
g2.addEdge(2,3);
g2.addEdge(3,4);
g2.addEdge(2,5);
g2.addEdge(6,1);
g2.addEdge(6,7);
g2.addEdge(7,8);
g2.addEdge(8,6);
if(g2.isCyclic())
std::cout << "Graph contains cycle"<<std::endl;
else
std::cout << "Graph doesn't contain cycle"<<std::endl;
return 0;
}