Skip to content

Commit 9985538

Browse files
Merge pull request #572 from Sanjanabharadwaj25/TSP
Added Travelling Salesperson Problem
2 parents f73210d + 9d328f0 commit 9985538

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Dynamic Programming/TSP.java

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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;
43+
if(start == n-1)
44+
{
45+
return (c[tour[n-1]][tour[n]] + c[tour[n]][1]);
46+
}
47+
for(i=start+1; i<=n; i++)
48+
{
49+
for(j=1; j<=n; j++)
50+
temp[j] = tour[j];
51+
temp[start+1] = tour[i];
52+
temp[i] = tour[start+1];
53+
if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)
54+
{
55+
mincost = c[tour[start]][tour[i]] + ccost;
56+
for(k=1; k<=n; k++)
57+
mintour[k] = temp[k];
58+
}
59+
}
60+
for(i=1; i<=n; i++)
61+
tour[i] = mintour[i];
62+
return mincost;
63+
}
64+
}
65+

0 commit comments

Comments
 (0)