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

Detect a cycle in Undirected Graph : Breadth-First Search #43

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool checkForCycle(int s, int V, vector<int> adj[], vector<int> &visited)
{
// Create a queue for BFS
queue<pair<int, int>> q;
visited[s] = true;
q.push({s, -1});
while (!q.empty())
{
int node = q.front().first;
int par = q.front().second;
q.pop();

for (auto it : adj[node])
{
if (!visited[it])
{
visited[it] = true;
q.push({it, node});
}
else if (par != it)
return true;
}
}
return false;
}
bool isCycle(int V, vector<int> adj[])
{
vector<int> vis(V - 1, 0);
for (int i = 1; i <= V; i++)
{
if (!vis[i])
{
if (checkForCycle(i, V, adj, vis))
return true;
}
}
}
};

void addEdge(vector<int> adj[],int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
int main()
{
vector<int> adj[5];

addEdge(adj,0,1);
addEdge(adj,0,2);
addEdge(adj,2,3);
addEdge(adj,1,3);
addEdge(adj,2,4);

Solution obj;
int num=obj.isCycle(5, adj);
if(num==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;

return 0;
}