Professional Documents
Culture Documents
167 - Amaankhanpathan - TSP DP PDF
167 - Amaankhanpathan - TSP DP PDF
167 - Amaankhanpathan - TSP DP PDF
Assignment No :- 07
1. Define a state space: The state space of the problem consists of all possible subsets of
cities that the salesman can visit, along with the city that the salesman is currently in.
For example, if there are n cities, then there are 2^n possible subsets of cities,
including the empty subset (representing the case where the salesman has visited no
cities yet).
2. Define a cost function: The cost function assigns a cost to each possible transition
between states. In this case, the cost of transitioning from state A (representing a
subset of cities) to state B (representing a subset of cities that includes city i) is the
minimum cost of any path that starts at the starting city, visits all cities in subset A
exactly once (not including city i), and ends at city i.
3. Fill in a table of costs: Starting with the smallest possible subsets (i.e., those
containing only the starting city), fill in a table of costs for all possible subsets of
cities. This can be done using a bottom-up approach, where the cost of each subset is
computed from the costs of its sub-subsets.
4. Find the optimal solution: Once the table of costs has been filled in, the optimal
solution can be found by starting at the starting city and repeatedly choosing the next
city with the lowest cost, until all cities have been visited. The cost of the optimal
solution is the sum of the costs of these transitions.
Time Complexity :-
The time complexity of the dynamic programming approach for TSP is O(n^2 * 2^n),
where n is the number of cities. While this approach is not practical for large TSP
instances, it can be used to solve smaller instances optimally.
Aim :- Design & Implement Travelling salespersons Problem using
Dynamic Programming. Also calculate the Time complexity for this
algorithm
Program Code :-
#include<iostream>
void takeInput()
int i, j;
cin>> n;
completed[i] = 0;
cout<< "\n";
int least(int c)
int i, nc = 999;
kmin = ary[c][i];
nc = i;
if(min != 999)
cost += kmin;
return nc;
int i, ncity;
completed[city] = 1;
cout << city + 1 << "--->";
ncity = least(city);
if (ncity == 999)
ncity = 0;
cost += ary[city][ncity];
return;
mincost(ncity);
int main()
takeInput();
mincost(0);
return 0;
}
Output :-