Skip to content

Create graph-cycle_detection.cpp #62

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
96 changes: 96 additions & 0 deletions Algorithms/graph-cycle_detection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@

#include <bits/stdc++.h>
using namespace std;
class Graph {


int V;
list<int>* adj;
bool isCyclicUtil(int v, bool visited[], int parent);

public:

Graph(int V);


void addEdge(int v, int w);


bool isCyclic();
};

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

void Graph::addEdge(int v, int w)
{

.
adj[v].push_back(w);


adj[w].push_back(v);
}

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


visited[v] = true;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i) {


if (!visited[*i]) {
if (isCyclicUtil(*i, visited, v))
return true;
}

else if (*i != parent)
return true;
}
return false;
}

bool Graph::isCyclic()
{


bool* visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;


for (int u = 0; u < V; u++) {


if (!visited[u])
if (isCyclicUtil(u, visited, -1))
return true;
}
return false;
}


int main()
{
Graph g1(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.isCyclic() ? cout << "Graph contains cycle\n"
: cout << "Graph doesn't contain cycle\n";

Graph g2(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.isCyclic() ? cout << "Graph contains cycle\n"
: cout << "Graph doesn't contain cycle\n";

return 0;
}