#include<bits/stdc++.h>
using namespace std;
bool iscycle(list<int> *adj,bool *visited,int i,int parent){
visited[i] = true;
for(auto j : adj[i]){
if(!visited[j])
if(iscycle(adj,visited,j,i))
return true;
else if(j != parent)
return true;
}
return false;
}
bool solve(vector<vector<int>> vect,int v){
list<int> *adj = new list<int>[v];
int i;
for(i = 0;i < vect.size();i++){
adj[vect[i][0]].push_back(vect[i][1]);
adj[vect[i][1]].push_back(vect[i][0]);
}
bool *visited = new bool[v];
for(i = 0;i < v;i++)
visited[i] = false;
int parent = -1;
for(i = 0;i < v;i++)
if(!visited[i]){
parent = -1;
if(iscycle(adj,visited,i,parent))
return true;
}
return false;
}
int main(){
std::vector<vector<int>> vect{{0,1},{1,2},{2,3}};
cout<<solve(vect,4)<<endl;
return 0;
}
This code to detect cycle in undirected graph is failing on some test cases such as when there are 4 vertices and every two vertices are connected as specified by vector "vect". For this particular test case the answer should be 0(i.e. there is no cycle detected) but the answer code is producing is 1. I cannot understand what is the error.