I am trying to implement the Traveling Salesman Problem and I need to return the path that lead to the minimum cost. I have a distance matrix, and this is the code:
static int TSP(int[][] distance, boolean[] visitCity, int currPos, int cities, int count, int cost, int result)
{
if (count == cities && distance[currPos][0] > 0) {
result = Math.min(result, cost + distance[currPos][0]);
return result;
}
for (int i = 0; i < cities; i++)
{
if (visitCity[i] == false && distance[currPos][i] > 0)
{
visitCity[i] = true;
result = TSP(distance, visitCity, i, cities, count + 1, cost + distance[currPos][i], result);
visitCity[i] = false;
}
}
return result;
}
I call this method like this:
boolean[] visitCity = new boolean[cities];
visitCity[0] = true;
int result = Integer.MAX_VALUE;
result = TSP(distance, visitCity, 0, cities, 1, 0, result);
In the end, the algorithm print the cost of the path, but I also need it to print the path that lead to this. Like "0->1->3->2->etc->0". Is there any posibility to achieve that?
I remodeled your algorithm into ObjectOriented stlye, to prevent passing too many arguments, and ease access to result values.
I could have returned Pair<costs, path>, but the OO style fits better in Java and allows easier access/maintenance.
The test method (main) print the calculated distance matrix first, then uses each city as starting and end place and prints the results for it.
Note that instead of the
Stack<Integer>path tracer I am now using indexed arrays, they are faster and easier to rewrite.I ran my test with this sexy piece of map to prevent possible first-choice-errors on local minimums:
Output: