I have to use the union find algorithm to solve the traveling salesman problem. I prettymuch got it done except for one problem I've just discovered. As it processes each edge, it will check for a cycle, which is done with the whole parent array thing. The problem is that, when it gets to the last edge I need to add to complete the problem, since it is technically a cycle, it does not add the edge, so the path can not be completed. How can I differentiate a useless cycle from the cycle indiicating that we are done?
Here's the code I got so far
private int[] parent; //parent of each vertex
private int[] connection; //number of edges coming from a given vertex
private int[] subsize; //size of each subtree
boolean donepath;
public void GreedyAlgo(){
ArrayList<Edge> newedges = new ArrayList<Edge>();
for(int i = 0; i<graph.realedge.size();i++){
if(donepath) break;
Edge e= graph.realedge.get(i);
int x = e.in1;
int y = e.in2;
if(unionFind(x,y) && !thirdEdge(x,y)){
newedges.add(e);
}
else{
}
}
}
public int findParent(int i){
if (parent[i] != i)
return findParent(parent[i]);
return parent[i];
}
public boolean unionFind(int x, int y){
int xx = findParent(x);
int yy = findParent(y);
if(xx == yy){
if(subsize[xx]== n){
donepath = true;
return true;
}
return false;
}
else{
if( subsize[xx] < subsize[yy]){
parent[xx] = yy;
subsize[yy]+=subsize[xx];
}
else if( subsize[xx] > subsize[yy]){
parent[yy] = xx; subsize[xx]+=subsize[yy];
}
else{
parent[yy] = xx;
subsize[xx]+=subsize[yy];
}
connection[x]++;
connection[y]++;
}
return true;
}
public boolean makesCycle(int x, int y){
int xx = findParent(x);
int yy = findParent(y);
if(xx == yy){
return true;
}
return false;
}
Here are the edges it goes through in order
0-0,
1-1,
2-2,
3-3,
4-4,
0-4 should get added,
2-3 should get added,
3-2,
4-0,
0-1 should get added,
0-2 ,
0-3,
1-0,
1-4,
2-0,
3-0,
4-1,
1-3 should get added,
3-1,
2-4 should get added......but doesnt,
3-4,
4-2,
4-3,
1-2,
2-1,