简体   繁体   中英

Error in detecting cycle in undirected graph code

#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(ie there is no cycle detected) but the answer code is producing is 1. I cannot understand what is the error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM