I am trying to implement the algorithm to solve the Travelling Salesman Problem.
I know that it is NP-Hard but I only need to solve it for 20 cities. I want to have an excat result and want to use the dynamic programming algorithm.
With my current implementation I am getting an java heap space error. This happens because I create an solution matrix with a index of "1 << n".
I can´t find any information related to this problem. Only found some information for max 10 cities.
Can anyone help me?
This is my code for TSP:
int n = dist.length;
int[][] dp = new int[n][n];
for (int[] d : dp)
Arrays.fill(d, Integer.MAX_VALUE / 2);
dp[1][0] = 0;
for (int mask = 1; mask < 1 << n; mask += 2) {
for (int i = 1; i < n; i++) {
if ((mask & 1 << i) != 0) {
for (int j = 0; j < n; j++) {
if ((mask & 1 << j) != 0) {
dp[mask][i] = Math.min(dp[mask][i], dp[mask ^ (1 << i)][j] + dist[j][i]);
}
}
}
}
}
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
res = Math.min(res, dp[(1 << n) - 1][i] + dist[i][0]);
}
// reconstruct path
int cur = (1 << n) - 1;
int[] order = new int[n];
int last = 0;
for (int i = n - 1; i >= 1; i--) {
int bj = -1;
for (int j = 1; j < n; j++) {
if ((cur & 1 << j) != 0 && (bj == -1 || dp[cur][bj] + dist[bj][last] > dp[cur][j] + dist[j][last])) {
bj = j;
}
}
order[i] = bj;
cur ^= 1 << bj;
last = bj;
}
System.out.println(Arrays.toString(order));
return res;