C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm

This C++ program implements the Travelling Salesman Problem which computes the minimum cost required to visit all the nodes by traversing across the edges only once.

Here is the source code of the C++ program to display the minimum cost by taking an undirected graph as input. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2. * C++ Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
  3.  */
  4. #include<stdio.h>
  5. #include<conio.h>
  6. #include<iostream>
  7. using namespace std;
  8. int c = 0,cost = 999;
  9. int graph[4][4] = { {0, 10, 15, 20},
  10.                     {10, 0, 35, 25},
  11.                     {15, 35, 0, 30},
  12.                     {20, 25, 30, 0}
  13.                   };
  14. void swap (int *x, int *y)
  15. {
  16.     int temp;
  17.     temp = *x;
  18.     *x = *y;
  19.     *y = temp;
  20. }
  21. void copy_array(int *a, int n)
  22. {
  23.     int i, sum = 0;
  24.     for(i = 0; i <= n; i++)
  25.     {
  26.         sum += graph[a[i % 4]][a[(i + 1) % 4]];
  27.     }
  28.     if (cost > sum)
  29.     {
  30.         cost = sum;
  31.     }
  32. }  
  33. void permute(int *a, int i, int n) 
  34. {
  35.    int j, k; 
  36.    if (i == n)
  37.    {
  38.         copy_array(a, n);
  39.    }
  40.    else
  41.    {
  42.         for (j = i; j <= n; j++)
  43.         {
  44.             swap((a + i), (a + j));
  45.             permute(a, i + 1, n);
  46.             swap((a + i), (a + j));
  47.         }
  48.     }
  49. } 
  50. int main()
  51. {
  52.    int i, j;
  53.    int a[] = {0, 1, 2, 3};  
  54.    permute(a, 0, 3);
  55.    cout<<"minimum cost:"<<cost<<endl;
  56.    getch();
  57. }

Output
minimum cost:80

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.