Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
AIM:
To implement travelling salesman problem using dynamic programming.
SOFTWARE USED:
Ubuntu 16.04 in VM Virtual Box.
PSEUDOCODE:
TSP(c)
{
for i = 1 to n
{
if((ary[c][i] is not equal to 0)&&(completed[i] is equal to 0))
if(ary[c][i]+ary[i][c] is less than min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
return nc;
}
Page | 90
SOURCE CODE:
#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
completed[i]=0;
}
Page | 91
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
}
}
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
Page | 92
int i,nc=999;
int min=999,kmin;
if(min!=999)
cost+=kmin;
return nc;
}
int main()
{
takeInput();
printf("\n\nThe Path is:\n");
mincost(0);
printf("\n\nMinimum cost is %d\n ",cost);
return 0;
}
Page | 93
ANALYSIS:
After reaching ith node, finding the remaining minimum distance to that ith node is a sub-
problem.
If we solve recursive equation we will get total (n-1) 2(n-2) sub-problems, which is O (n2n).
Each sub-problem will take O (n) time (finding path to remaining (n-1) nodes).
Therefore, total time complexity is O (n2n) * O (n) = O (n22n)
OUTPUT:
Enter the number of cities: 4
Enter the Cost Matrix
Enter Elements of Row: 1
0413
Enter Elements of Row: 2
4021
Enter Elements of Row: 3
1205
Enter Elements of Row: 4
3150
The cost list is:
0413
4021
1205
3150
Minimum cost is 7
Page | 94