Given an Undirected Graph with V vertices (Numbered from 0 to V-1) and E edges, check whether it contains any cycle or not.
Detect cycle in an undirected graph | Practice | GeeksforGeeks
Detect cycle in an undirected graph - GeeksforGeeks
class Solution
{
public:
//Function to detect cycle in an undirected graph.
bool isCycle(int V, vector<int> adj[])
{
vector<int> visited(V,0);
for(int u=0;u<V;u++)
{
if(!visited[u])
{
if(dfs(u,adj,visited,-1))
return true;
}
}
return false;
}
bool dfs(int u,vector<int> adj[],vector<int> &visited,int parent)
{
if(visited[u])
return true;
visited[u] = 1;
for(int v:adj[u])
{
if(!visited[v])
{
if(dfs(v,adj,visited,u))
return true;
}
**else if(v!=parent)**
return true;
}
return false;
}
};
Commutable Islands (Kruskal's Algorithm using Disjoint Sets)