-2
#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.

Nicol Bolas
  • 378,677
  • 53
  • 635
  • 829
  • You have represented the adjacency list as a list, should it be a list of list as the adjacency list will be 2D? Can you explain how you are using `adj` for storing the edge data ? – Deepak Patankar Sep 13 '20 at 06:28
  • @DeepakPatankar It is actually a 2d list. I am creating [v] number of list data as I have v nodes. Just like when we create an array using new (int *a = new int[5] ) . Btw the code is compiling correctly and adjacency list is also correctly storing the data. I have checked this by printing the adjacency list. – user13556745 Sep 13 '20 at 11:10

1 Answers1

0

The else in iscycle goes with the second, innermost if, not the first, misleading indentation notwithstanding. Add braces as needed.

Igor Tandetnik
  • 45,980
  • 4
  • 51
  • 75