Skip to content
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.Arrays;

public class TSP {
static int n;
static int MAX = 1000000;
static int[][] dist;
static int[][] memo;
static int[][] parent;

static int tsp(int i, int mask) {
if (mask == (1 << n) - 1) {
return dist[i][0];
}

if (memo[i][mask] != -1) {
return memo[i][mask];
}

int res = MAX;

for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
int newRes = dist[i][j] + tsp(j, mask | (1 << j));
if (newRes < res) {
res = newRes;
parent[i][mask] = j;
}
}
}

return memo[i][mask] = res;
}

static void printPath(int i, int mask) {
System.out.print(i + " → ");
if (mask == (1 << n) - 1) {
System.out.println(0);
return;
}
int nextCity = parent[i][mask];
printPath(nextCity, mask | (1 << nextCity));
}

public static void main(String[] args) {
n = 4;
dist = new int[][] {
{ 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 }
};

memo = new int[n][1 << n];
parent = new int[n][1 << n];

for (int[] row : memo) {
Arrays.fill(row, -1);
}

int minCost = tsp(0, 1);

System.out.println("The minimum cost of the tour is: " + minCost);

System.out.print("The optimal path is: ");
printPath(0, 1);
}
}