Travelling Salesman (DP)

Solves the standard travelling salesman problem with DP. Runs on O(N*2^N), only works for N < 20 or so.

Java
public static int minDist(int[] arr, int b, int s, int x) { if (x == 0) {         return 2*finalD[0][s+1] ; }     if (DP[b][s] != -1) return DP[b][s] ; int[] newArr = new int[arr.length] ; for (int j = 0 ; j < arr.length ; j ++) newArr[j] = arr[j] ; int min = 999999 ; for (int i = 0 ; i < arr.length ; i ++) {         if (arr[i] == 1) {             newArr[i] = 0 ; int tb = b - (1<<i) ; min = Math.min(min, minDist(newArr,tb,i,x-1) + finalD[i+1][s+1] + finalD[s+1][0] - finalD[i+1][0]) ; newArr[i] = 1 ; }     }      return DP[b][s] = min ; } For this algorithm to work, you need the following:

1) A NXN matrix of the shortest path from Point A to Point B, called finalD[][].

2) The place that you intend to start and end is put into the 0th array slot.

3) To get the shortest TSP path, you want to call the function with minDist( {1,1,1...1},1<<N, S, N), and try this function for all S (that is, if N = 10, try S = 0, S = 1.. S = 9). Take the minimum of these.