Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cycle Detection in A Cyclic Directed Graph #21

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions C++/DetectCycleDirected.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#include<iostream>
#include<queue>
#include<map>
#include<list>

using namespace std;

class Graph{
int V;
list<int> *adjList;
bool isCyclicUtil(int v, bool visited[], bool recStack[]);

public:

Graph(int V);
void addEdge(int u, int v);
bool isCyclic();
};

Graph::Graph(int V){
this->V = V;
adjList = new list<int>[V];
}

void Graph::addEdge(int u, int v){
adjList[u].push_back(v);
}

bool Graph::isCyclicUtil(int v, bool visited[], bool recStack[]){

if(!visited[v]){
visited[v] = true;
recStack[v] = true;
}

for(auto x: adjList[v]){
if(!visited[x] and isCyclicUtil(x, visited, recStack)){
return true;
}else if(recStack[x]){
return true;
}
}

recStack[v] = false;

return false;
}

bool Graph::isCyclic(){

bool *visited = new bool[V];
bool *recStack = new bool[V];

for(int i = 0; i < V; i++){
visited[i] = false;
recStack[i] = false;
}

for(int i = 0; i < V; i++){
if(!visited[i] and isCyclicUtil(i, visited, recStack)){
return true;
}
}

return false;
}

int main(void){

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())
cout << "Graph contains cycle" << endl;
else
cout << "Graph doesn't contain cycle" << endl;

return 0;
}