I'm a beginner, and I'm trying to write a working travelling salesman problem using dynamic programming approach.
This is the code for my compute function:
public static int compute(int[] unvisitedSet, int dest) { if (unvisitedSet.length == 1) return distMtx[dest][unvisitedSet[0]]; int[] newSet = new int[unvisitedSet.length-1]; int distMin = Integer.MAX_VALUE; for (int i = 0; i < unvisitedSet.length; i++) { for (int j = 0; j < newSet.length; j++) { if (j < i) newSet[j] = unvisitedSet[j]; else newSet[j] = unvisitedSet[j+1]; } int distCur; if (distMtx[dest][unvisitedSet[i]] != -1) { distCur = compute(newSet, unvisitedSet[i]) + distMtx[unvisitedSet[i]][dest]; if (distMin > distCur) distMin = distCur; } else { System.out.println("No path between " + dest + " and " + unvisitedSet[i]); } } return distMin; }
The code is not giving me the correct answers, and I'm trying to figure out where the error is occurring. I think my error occurs when I add: distCur = compute(newSet, unvisitedSet[i]) + distMtx[unvisitedSet[i]][dest]; So I've been messing around with that part, moving the addition to the very end right before I return distMin and so on... But I couldn't figure it out.
Although I'm sure it can be inferred from the code, I will state the following facts to clarify.
distMtx stores all the intercity distances, and distances are symmetric, meaning if distance from city A to city B is 3, then the distance from city B to city A is also 3. Also, if two cities don't have any direct paths, the distance value is -1.
Any help would be very much appreciated! Thanks!