@@ -7,7 +7,7 @@ public class TSP {
7
7
static int[][] memo;
8
8
static int[][] parent;
9
9
10
- static int tsp(int i, int mask) {
10
+ public static int tsp(int i, int mask) {
11
11
if (mask == (1 << n) - 1) {
12
12
return dist[i][0];
13
13
}
@@ -31,37 +31,85 @@ public class TSP {
31
31
return memo[i][mask] = res;
32
32
}
33
33
34
- static void printPath(int i, int mask) {
35
- System.out.print (i + " → ");
34
+ public static String printPath(int i, int mask) {
35
+ StringBuilder path = new StringBuilder (i + " → ");
36
36
if (mask == (1 << n) - 1) {
37
- System.out.println (0);
38
- return;
37
+ path.append (0);
38
+ return path.toString() ;
39
39
}
40
40
int nextCity = parent[i][mask];
41
- printPath(nextCity, mask | (1 << nextCity));
41
+ path.append(printPath(nextCity, mask | (1 << nextCity)));
42
+ return path.toString();
42
43
}
43
44
44
- public static void main(String[] args) {
45
- n = 4;
46
- dist = new int[][] {
45
+ public static void initialize(int[][] distanceMatrix) {
46
+ n = distanceMatrix.length;
47
+ dist = distanceMatrix;
48
+ memo = new int[n][1 << n];
49
+ parent = new int[n][1 << n];
50
+ for (int[] row : memo) {
51
+ Arrays.fill(row, -1);
52
+ }
53
+ }
54
+ }
55
+ import org.junit.Test;
56
+ import static org.junit.Assert.*;
57
+
58
+ public class TSPTest {
59
+
60
+ @Test
61
+ public void testTSPWithSmallGraph() {
62
+ int[][] distanceMatrix = {
47
63
{ 0, 10, 15, 20 },
48
64
{ 10, 0, 35, 25 },
49
65
{ 15, 35, 0, 30 },
50
66
{ 20, 25, 30, 0 }
51
67
};
52
68
53
- memo = new int[n][1 << n];
54
- parent = new int[n][1 << n];
69
+ TSP.initialize(distanceMatrix);
55
70
56
- for (int[] row : memo) {
57
- Arrays.fill(row, -1);
58
- }
71
+ int minCost = TSP.tsp(0, 1);
72
+
73
+ assertEquals(80, minCost);
74
+ }
75
+
76
+ @Test
77
+ public void testOptimalPath() {
78
+ int[][] distanceMatrix = {
79
+ { 0, 10, 15, 20 },
80
+ { 10, 0, 35, 25 },
81
+ { 15, 35, 0, 30 },
82
+ { 20, 25, 30, 0 }
83
+ };
84
+
85
+ TSP.initialize(distanceMatrix);
86
+
87
+ TSP.tsp(0, 1);
88
+
89
+ String expectedPath = "0 → 1 → 3 → 2 → 0";
90
+ String actualPath = TSP.printPath(0, 1);
91
+
92
+ assertEquals(expectedPath, actualPath);
93
+ }
94
+
95
+ @Test
96
+ public void testDifferentGraph() {
97
+ int[][] distanceMatrix = {
98
+ { 0, 29, 20, 21 },
99
+ { 29, 0, 15, 17 },
100
+ { 20, 15, 0, 28 },
101
+ { 21, 17, 28, 0 }
102
+ };
103
+
104
+ TSP.initialize(distanceMatrix);
59
105
60
- int minCost = tsp(0, 1);
106
+ int minCost = TSP.tsp(0, 1);
107
+
108
+ assertEquals(75, minCost);
61
109
62
- System.out.println("The minimum cost of the tour is: " + minCost);
110
+ String expectedPath = "0 → 2 → 1 → 3 → 0";
111
+ String actualPath = TSP.printPath(0, 1);
63
112
64
- System.out.print("The optimal path is: ");
65
- printPath(0, 1);
113
+ assertEquals(expectedPath, actualPath);
66
114
}
67
115
}
0 commit comments