class Solution {
public:
// Function to detect cycle in an undirected graph.
bool dfs(int node, int parent, vector adj[], vector & visited) {
visited[node] = true;
for(int neigh : adj[node]) {
if(!visited[neigh] ) {
if(dfs(neigh, node, adj, visited)) {
return true;
}
}
else if(neigh != parent) {
return true;
}
}
return false;
}
bool isCycle(int V, vector adj[]) {
bool res = false;
vector visited(V + 2, false);
for(int i = 0; i < V; i++) {
if(!visited[i]) {
if(dfs(i, -1, adj, visited)) {
return true;
}
}
}
return false;
}
};