-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Traveling_SalesmanDP.java
134 lines (86 loc) · 2.71 KB
/
Traveling_SalesmanDP.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
Travelling Salesman Problem states-
A salesman has to visit every city exactly once.
He has to come back to the city from where he starts his journey.
We need to find-
What is the shortest possible route that the salesman must follow to complete his tour?
*/
import java.util.*;
import java.lang.*;
//Travelling Salesman Problem using Dynamic programming
public class Traveling_SalesmanDP {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int c[][]=new int[10][10], tour[]=new int[10];
int i, j,cost;
System.out.println("");
// taking no. of cities input from user
System.out.print("Enter No. of Cities: ");
int n = in.nextInt();
if(n==1)
{
System.out.println("");
System.out.println("Path is not possible!");
System.exit(0);
}
System.out.println("");
System.out.println("Enter the Cost Matrix:");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
c[i][j] = in.nextInt();
for(i=1;i<=n;i++)
tour[i]=i;
cost = tspdp(c, tour, 1, n);
System.out.println("");
//printing out the path(min cost)
System.out.print("The Optimal Tour is: ");
for(i=1;i<=n;i++)
System.out.print(tour[i]+"->");
System.out.println("1");
System.out.println("");
//cost of the optimal path
System.out.println("Minimum Cost: "+cost);
}
static int tspdp(int c[][], int tour[], int start, int n)
{
int mintour[]=new int[10], temp[]=new int[10], mincost=999,ccost, i, j, k;
if(start == n-1)
{
return (c[tour[n-1]][tour[n]] + c[tour[n]][1]);
}
for(i=start+1; i<=n; i++)
{
for(j=1; j<=n; j++)
temp[j] = tour[j];
temp[start+1] = tour[i];
temp[i] = tour[start+1];
if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)
{
mincost = c[tour[start]][tour[i]] + ccost;
for(k=1; k<=n; k++)
mintour[k] = temp[k];
}
}
for(i=1; i<=n; i++)
{
tour[i] = mintour[i];
}
return mincost;
}
}
/*
Sample I/O:
Enter No. of Cities: 4
Enter the Cost Matrix:
4 8 6 3
4 3 2 7
1 2 3 0
1 6 1 7
The Optimal Tour is: 1->4->3->2->1
Minimum Cost: 10
Time Complexity: O(2^n*n^2)
Space Complexity: O(2^n)
(here n is no. of nodes in the graph(creating graph
to find optimal path))
*/