I'm working on a small project for solving TSP but am experiencing a problem. The idea is to optimize a local part of a non-optimal path by simply finding the best combination. This is accomplished by a simple recursive permutation generating function.
What I want to do now is check whether the current solution has any potential for improvment (logic: not to call permutation function if weight of solution is more than current best).
The problem that I'm having is that the current implementation does improve the solution but does not make it optimal (I've compared the results to a simple brute-force search). I would appreciate if you'd point out my logic flaws or/ and mistakes. M - is cost matrix. help - current solution, best - best solution (class variables)
void City::Generate(int** M, int* help, int k, int &auxcost, int* best) {
int cost2 = 0; // текущая цена
if (k == range){
for (int i = 0; i < range - 1; i++)
cost2 += M[help[i]][help[i + 1]];
if (cost2 < auxcost ){
auxcost = cost2;
memcpy(best, help,range *sizeof(int));
changed = true;
}
}
else{
for (int j2 = k; j2<range; j2++){
swap(help[k], help[j2]);
for (int i = 0; i < range - 1; i++)
tcost += M[help[i]][help[i + 1]];
if (tcost <= auxcost)
Generate(M, help, k + 1, start, end, auxcost, best);
swap(help[k], help[j2]);
}
}
}