I am trying to generate a fully random hamiltonian cycle in an undirected graph which I know to be complete with numverts vertices. I have previously initialized the arrays outgoing and incoming. outgoing[i] represents where the outgoing edge from vertex i points, and incoming[i] represents whether a vertex has an incoming edge. The following code attempts to go along each randomly created edge and create another edge, and repeat the process, and finally connect the last vertex back to 0; However, it seems to fail with probability 1/numverts, and still have at least one -2 in outgoing[]. What could be going wrong?
for(int i = 0; i < numverts; i++) //fill outgoing and incoming with null data
{
outgoing[i] = -2;
incoming[i] = false;
}
for(int i = 0; i < numverts; i++)
{
int numtotest = (int)(numverts*Math.random());
if((!incoming[numtotest]) &&(outgoing[numtotest]==-2)) //ensure that the graph had neither incoming nor outgoing edges before generation
{
outgoing[currentvert] = numtotest; //create the random edge
incoming[numtotest] = true;
currentvert = numtotest; //recur along newly created edge
}
else if(i == numverts-1)
{
outgoing[currentvert] = 0;
incoming[0] = true; //reconnect final vertex to 0
}
else
{
i--; //decrement counter if vertex i already had an edge outgoing or incoming
}
}
Aucun commentaire:
Enregistrer un commentaire