Skip to content

Commit 3696395

Browse files
authored
Solved TravelingSalesManProblem Using DynamicProgramming(memoization)
In the above code, we implement a solution to the Traveling Salesman Problem (TSP) using dynamic programming with memoization. The algorithm calculates the shortest possible route that visits a set of cities exactly once and returns to the starting city by recursively exploring all possible paths and storing the results of subproblems to avoid redundant calculations. The program outputs both the minimum cost of the tour and the optimal path taken.
1 parent c0f3524 commit 3696395

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.util.Arrays;
2+
3+
public class TSP {
4+
static int n;
5+
static int MAX = 1000000;
6+
static int[][] dist;
7+
static int[][] memo;
8+
static int[][] parent;
9+
10+
static int tsp(int i, int mask) {
11+
if (mask == (1 << n) - 1) {
12+
return dist[i][0];
13+
}
14+
15+
if (memo[i][mask] != -1) {
16+
return memo[i][mask];
17+
}
18+
19+
int res = MAX;
20+
21+
for (int j = 0; j < n; j++) {
22+
if ((mask & (1 << j)) == 0) {
23+
int newRes = dist[i][j] + tsp(j, mask | (1 << j));
24+
if (newRes < res) {
25+
res = newRes;
26+
parent[i][mask] = j;
27+
}
28+
}
29+
}
30+
31+
return memo[i][mask] = res;
32+
}
33+
34+
static void printPath(int i, int mask) {
35+
System.out.print(i + " → ");
36+
if (mask == (1 << n) - 1) {
37+
System.out.println(0);
38+
return;
39+
}
40+
int nextCity = parent[i][mask];
41+
printPath(nextCity, mask | (1 << nextCity));
42+
}
43+
44+
public static void main(String[] args) {
45+
n = 4;
46+
dist = new int[][] {
47+
{ 0, 10, 15, 20 },
48+
{ 10, 0, 35, 25 },
49+
{ 15, 35, 0, 30 },
50+
{ 20, 25, 30, 0 }
51+
};
52+
53+
memo = new int[n][1 << n];
54+
parent = new int[n][1 << n];
55+
56+
for (int[] row : memo) {
57+
Arrays.fill(row, -1);
58+
}
59+
60+
int minCost = tsp(0, 1);
61+
62+
System.out.println("The minimum cost of the tour is: " + minCost);
63+
64+
System.out.print("The optimal path is: ");
65+
printPath(0, 1);
66+
}
67+
}

0 commit comments

Comments
 (0)