Loading…
DAA · Dynamic programming · Program 19 · In the record
Write a program in c to solve the travelling salesman problem using dynamic programming and find its execution time using the time function.
Algorithm: TSP(cost, n)
(g(i, S) = cheapest path that starts at city i, visits every city in set S once, and ends at city 1)
1. Start
2. For i <- 2 to n do
3. g(i, {}) <- cost[i][1]
4. For each set S not containing city 1, in increasing size do
5. For each city i not in S do
6. g(i, S) <- infinity
7. For each city k in S do
8. if cost[i][k] + g(k, S - {k}) < g(i, S) then
9. g(i, S) <- cost[i][k] + g(k, S - {k})
10. next(i, S) <- k
11. print "Minimum cost" g(1, {2, 3, ..., n})
12. Follow next(i, S) from city 1 to print the tour
13. Stop1#include<stdio.h>2#include<time.h>3 4int cost[15][15];5int g[1<<15][15],nxt[1<<15][15];6 7int main() {8 int n,i,j,k,S,full,count=0;9 printf("Enter the number of cities:");10 scanf("%d",&n);11 printf("Enter the %dx%d cost matrix:\n",n,n);12 for(i=0;i<n;i++)13 for(j=0;j<n;j++)14 scanf("%d",&cost[i][j]);15 16 clock_t start=clock();17 // S is a bitmask of cities; bit 0 (city 1) is never in S18 full=(1<<n)-1;19 for(i=0;i<n;i++)20 g[0][i]=cost[i][0];21 for(S=1;S<=full;S++) {22 if(S&1)23 continue;24 for(i=0;i<n;i++) {25 if(S&(1<<i))26 continue;27 g[S][i]=999999999;28 for(k=1;k<n;k++) {29 if(S&(1<<k)) {30 count++;31 int c=cost[i][k]+g[S^(1<<k)][k];32 if(c<g[S][i]) {33 g[S][i]=c;34 nxt[S][i]=k;35 }36 }37 }38 }39 }40 S=full^1;41 clock_t end=clock();42 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;43 44 printf("\nMinimum cost of tour:%d",g[S][0]);45 printf("\nOptimal tour:1");46 i=0;47 while(S!=0) {48 k=nxt[S][i];49 printf(" -> %d",k+1);50 S=S^(1<<k);51 i=k;52 }53 printf(" -> 1");54 printf("\nNumber of comparisons:%d",count);55 printf("\nTime taken:%f seconds",time_taken);56 printf("\nTime complexity: O(n^2 * 2^n)");57 printf("\nSpace complexity: O(n * 2^n)");58 printf("\n");59 return 0;60}4 ⏎ 0 10 15 20 ⏎ 5 0 9 10 ⏎ 6 13 0 12 ⏎ 8 8 9 0Enter the number of cities:4 Enter the 4x4 cost matrix: 0 10 15 20 5 0 9 10 6 13 0 12 8 8 9 0 Minimum cost of tour:35 Optimal tour:1 -> 2 -> 4 -> 3 -> 1 Number of comparisons:24 Time taken:0.000008 seconds Time complexity: O(n^2 * 2^n) Space complexity: O(n * 2^n)
Run program 19 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.