Although the control isn't going to the if condition in isCyclic() function but still it is returning 1. When I uncomment the return 0 statement, it is indeed returning 0.
So, does an int function return 1 by default? I don't think so. It returns garbage value. But then why it is returning 1 here!!!
#include <bits/stdc++.h>
using namespace std;
class edge{
public:
int src,des;
};
class graph{
public:
int v,e;
edge *edges;
int edges_counter;
graph(int v, int e){
this->v = v;
this->e = e;
edges = new edge[e];
edges_counter = 0;
}
void addedge(int src, int des){
edges[edges_counter].src = src;
edges[edges_counter].des = des;
edges_counter++;
}
int find(int parent[], int i){
if(parent[i]==-1)
return i;
return find(parent, parent[i]);
}
void Union(int parent[], int x, int y){
parent[x] = y;
}
int isCyclic(){
int parent[v];
for(int j=0; j<v ;j++) parent[j] = -1;
for(int i=0; i<e; i++){
int first = find(parent, edges[i].src);
int second = find(parent, edges[i].des);
if(first==second){
cout <<"Hell";
return 1;
}
Union(parent, first, second);
}
//return 0; //here
}
};
int main(){
graph g(3,2);
g.addedge(0, 1);
g.addedge(0, 2);
cout << g.isCyclic() << endl;
if(g.isCyclic()==1) cout << "Grpah contains cycle\n";
else cout << "Grpah doesn't contain cycle\n";
}