| 1 | import java.util.Scanner; |
| 2 | public class TSP{ |
| 3 | public static void main(String[] args) |
| 4 | { |
| 5 | int c[][]=new int[10][10], tour[]=new int[10]; |
| 6 | Scanner in = new Scanner(System.in); |
| 7 | int i, j,cost; |
| 8 | System.out.println("** TSP DYNAMIC PROGRAMMING ***"); |
| 9 | System.out.println("Enter the number of cities: "); |
| 10 | int n = in.nextInt(); |
| 11 | if(n==1) |
| 12 | { |
| 13 | System.out.println("Path is not possible"); |
| 14 | System.exit(0); |
| 15 | } |
| 16 | System.out.println("Enter the cost matrix"); |
| 17 | for(i=1;i<=n;i++) |
| 18 | for(j=1;j<=n;j++) |
| 19 | c[i][j] = in.nextInt(); |
| 20 | System.out.println("The entered cost matrix is"); |
| 21 | for(i=1;i<=n;i++) |
| 22 | { |
| 23 | for(j=1;j<=n;j++) |
| 24 | { |
| 25 | System.out.print(c[i][j]+"\t"); |
| 26 | } |
| 27 | System.out.println(); |
| 28 | } |
| 29 | for(i=1;i<=n;i++) |
| 30 | tour[i]=i; |
| 31 | cost = tspdp(c, tour, 1, n); |
| 32 | System.out.println("The accurate path is"); |
| 33 | for(i=1;i<=n;i++) |
| 34 | System.out.print(tour[i]+"->"); |
| 35 | |
| 36 | System.out.println("1"); |
| 37 | System.out.println("The accurate mincost is "+cost); |
| 38 | System.out.println("*** ***** *****"); |
| 39 | } |
| 40 | static int tspdp(int c[][], int tour[], int start, int n) |
| 41 | { |
| 42 | int mintour[]=new int[10], temp[]=new int[10], mincost=999, ccost, i, j, k; |