1
+ import java .util .List ;
2
+ import java .util .ArrayList ;
3
+
4
+ public class TestGraphs {
5
+
6
+ public static List <Integer > solution ;
7
+ public static int bestTravelCost ;
8
+
9
+ public static void main (String [] args ) {
10
+ Graph g = new Graph (5 );
11
+
12
+ // add Edges
13
+ g .addEdge (0 , 1 , 5 );
14
+ g .addEdge (0 , 2 , 2 );
15
+ g .addEdge (0 , 3 , 3 );
16
+ g .addEdge (0 , 4 , 4 );
17
+ g .addEdge (1 , 2 , 3 );
18
+ g .addEdge (1 , 3 , 2 );
19
+ g .addEdge (1 , 4 , 2 );
20
+ g .addEdge (2 , 3 , 2 );
21
+ g .addEdge (2 , 4 , 4 );
22
+ g .addEdge (3 , 4 , 1 );
23
+
24
+ // print Graph
25
+ g .printGraph ();
26
+
27
+ // Naive Algorithm for TSP
28
+ TSPNaive (g );
29
+ }
30
+
31
+ public static void TSPNaive (Graph g ){
32
+ int v = g .getvCount ();
33
+
34
+ solution = new ArrayList <Integer >();
35
+ List <Integer > permutation = new ArrayList <Integer >();
36
+ for (int i = 0 ; i < v ; i ++){
37
+ solution .add (i );
38
+ permutation .add (i );
39
+ }
40
+ solution .add (0 );
41
+ permutation .add (0 );
42
+
43
+ int travelCost = calcTravelCost (g , permutation );
44
+ bestTravelCost = travelCost ;
45
+
46
+ permute (g , permutation , 1 , v -1 );
47
+
48
+ System .out .println ("\n Solution: " + bestTravelCost );
49
+ for (int i = 0 ; i < solution .size (); i ++){
50
+ System .out .print (solution .get (i ) + " " );
51
+ }
52
+ System .out .println ();
53
+ }
54
+
55
+ public static int calcTravelCost (Graph g , List <Integer > permutation ){
56
+ int [][] adj = g .getAdj ();
57
+ int v = g .getvCount ();
58
+ int travelCost = 0 ;
59
+
60
+ for (int i = 0 ; i < v ; i ++){
61
+ int startIndex = permutation .get (i );
62
+ int endIndex = permutation .get (i + 1 );
63
+ travelCost += adj [startIndex ][endIndex ];
64
+ }
65
+
66
+ return travelCost ;
67
+ }
68
+
69
+ public static void swapVertices (List <Integer > permutation , int indexA , int indexB ){
70
+ int valueA = permutation .get (indexA );
71
+ int valueB = permutation .get (indexB );
72
+
73
+ permutation .set (indexA , valueB );
74
+ permutation .set (indexB , valueA );
75
+ }
76
+
77
+ public static void permute (Graph g , List <Integer > permutation , int l , int r ){
78
+ if (l == r ){
79
+ int travelCost = calcTravelCost (g , permutation );
80
+
81
+ System .out .println ("\n Permutation: " + travelCost );
82
+ for (int i = 0 ; i < permutation .size (); i ++){
83
+ System .out .print (permutation .get (i ) + " " );
84
+ }
85
+ System .out .println ();
86
+
87
+ if (travelCost < bestTravelCost ){
88
+ bestTravelCost = travelCost ;
89
+ for (int i = 0 ; i < solution .size (); i ++){
90
+ solution .set (i , permutation .get (i ));
91
+ }
92
+ }
93
+ }
94
+ else {
95
+ for (int i = l ; i <= r ; i ++){
96
+ swapVertices (permutation , l , i );
97
+ permute (g , permutation , l +1 , r );
98
+ swapVertices (permutation , l , i );
99
+ }
100
+ }
101
+ }
102
+
103
+ }
0 commit comments