
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm
Here is a C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm.
Required functions and pseudocodes
Algorithm
Begin Initialize c = 0, cost = 1000; Initialize g[][]. function swap() is used to swap two values x and y. function cal_sum() to calculate the cost which take array a[] and size of array as input. Initialize sum = 0. for i = 0 to n compute s+= g[a[i %3]][a[(i+ 1) %3]]; if (cost >s) cost = s function permute() is used to perform permutation: if there is one element in array call cal_sum(). else for j = i to n swap (a+i) with (a + j) cal_sum(a+1,n) swap (a+i) with (a + j) End
Example Code
#include<iostream> using namespace std; int c = 0, cost = 1000; int g[3][3 ]={{1, 2, 3}, {4, 5, 8}, {6, 7, 10}}; void swap(int *x, int *y) { int t; t = *x; *x = *y; *y = t; } void cal_sum(int *a, int n) { int i, s= 0; for (i = 0; i <= n; i++) { s+= g[a[i %3]][a[(i+ 1) %3]]; } if (cost >s) { cost = s; } } void permute(int *a,int i,int n) { int j, k; if (i == n) { cal_sum (a,n); } else { for (j = i; j <= n; j++) { swap((a + i), (a + j)); cal_sum(a+1,n); swap((a + i), (a + j)); } } } int main() { int i, j; int a[] = {1,2,3}; permute(a, 0,2); cout << "minimum cost:" << cost << endl; }
Output
Comparing str1 and str2 using ==, Res: 0 Comparing str1 and str3 using ==, Res: 1 Comparing str1 and str2 using compare(), Res: -1024 Comparing str1 and str3 using compare(), Res: 0
- Related Articles
- C++ Program to Implement Nearest Neighbour Algorithm
- Travelling Salesman Problem
- C++ Program to Solve Travelling Salesman Problem for Unweighted Graph
- C++ Program to Implement Dijkstra’s Algorithm Using Set
- Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm
- C++ Program to Implement Network_Flow Problem
- C++ Program to Implement Kadane’s Algorithm
- C++ Program to Implement Johnson’s Algorithm
- C++ Program to Implement the RSA Algorithm
- C++ Program to Implement Coppersmith Freivald’s Algorithm
- C++ Program to Implement Modular Exponentiation Algorithm
- C++ Program to Implement Expression Tree Algorithm
- C++ Program to Implement Interpolation Search Algorithm
- C++ Program to Implement Extended Euclidean Algorithm
- C program to implement Euclid’ s algorithm

Advertisements