-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement_travelling_salesman.cpp
47 lines (42 loc) · 1.02 KB
/
implement_travelling_salesman.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* This program illustrates the implementation of the travelling salesman problem using dynamic programming*/
#include<iostream>
using namespace std;
#define INT_MAX 999999
int n;
int dist[10][10];
int VISITED;
int dp[16][4];
int travelling_salesman(int mask,int pos){
if(mask==VISITED){
return dist[pos][0];
}
if(dp[mask][pos]!=-1){
return dp[mask][pos];
}
int ans = INT_MAX;
for(int city=0;city<n;city++){
if((mask&(1<<city))==0){
int tempAns = dist[pos][city] + travelling_salesman( mask|(1<<city), city);
ans = min(ans, tempAns);
}
}
return dp[mask][pos] = ans;
}
int main(){
cin>>n;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cin>>dist[i][j];
}
}
VISITED = (1<<n) -1;
for(int i = 0; i < (1<<n); ++i){
for(int j = 0; j < n; ++j){
dp[i][j] = -1;
}
}
cout<<"Travelling Saleman Distance is "<<travelling_salesman(1,0);
return 0;
}