I was trying to solve the traveling salesman problem using C. I was successfully able to calculate the correct minimum distance, but I cannot seem to be able to generate the corresponding path. Note: I don't need to go back to the first city which is why function might be slightly different than the classics one.
The idea that I used to solve this problem is the following: I recursively call a function called the travelingSalesMan, if all the cities where visited (I keep track of the visited cities using an array visited) or the current path being followed is bigger than the previous one I just return the minimum between the current distance, that is stored in a variable, and the current min distance (set to max at the beginning).
I tried to keep track of the path using an array called currentPath as well as pathLen which tells me how many elements are in the path.
Here is the code I have right now:
int travelingSalesMan(int** distMatrix, int arrSize, int* visited, int currentCity, int* currentPath, int cur_dist, int min_dist, int* minPath, int pathLen){
if (complete(visited, arrSize) == arrSize) {
// minPath[index] = currentPath[index];
printf("Path len: %d\n", pathLen);
for(int i = 0; i<arrSize; i++){
minPath[i] = currentPath[i];
}
minPath[arrSize - 1] = currentCity;
return min(cur_dist, min_dist);
}
// no need to pursue the path that is not minimum
if(cur_dist >= min_dist){
pathLen--;
return min(cur_dist, min_dist);
}
for (int i = 0; i<arrSize; i++) {
if (visited[i] == 0 && i != currentCity) {
cur_dist += distMatrix[currentCity][i];
currentPath[pathLen++] = currentCity;
visited[i] = 1;
min_dist = travelingSalesMan(distMatrix, arrSize, visited, i, currentPath, cur_dist, min_dist, minPath, pathLen);
visited[i] = 0;
cur_dist -= distMatrix[currentCity][i];
pathLen--;
}
}
return min_dist;
}
I called the function above with the following parameters:
distance = travelingSalesMan(distMatrix, N, visited, 0, currentPath, 0, INT_MAX, minPath, 1);
For the given distMatrix:
[
{0 10 10 10 10}
{10 0 2 4 11}
{10 2 0 12 4}
{10 4 12 0 8}
{10 11 4 8 0}
]
The minimum weight is 20, so I am expecting to see a path such as:
0 3 1 2 4
Thanks!