// TSP.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
typedef struct _node_st{
bool inPath ;
int nextIndex;
_node_st():inPath(false),nextIndex(-1){
}
}Node,*NodePtr;
#define MAX 6
int dis[MAX][MAX]={
0, 10, 20, 30, 40, 50,
12, 0 ,18, 30, 25, 21,
23, 19, 0, 5, 10, 15,
34, 32, 4, 0, 8, 16,
45, 27, 11,10, 0, 18,
56, 22, 16,20, 12, 0
};
Node p[MAX];
void printPath();
//表示从begin开始,经过所有点后到达end的最小距离
int tsp(int beginIndex,int endIndex){
int result = 0xFFFFFFF;
bool isLast = true;
for(int i=0;i<MAX;i++){
if(i!=beginIndex){
if(!p[i].inPath){
isLast = false;
p[i].inPath = true;
int value = tsp(i,endIndex);
if(dis[beginIndex][i]+value<result){
p[beginIndex].nextIndex = i;
result = dis[beginIndex][i]+value;
if(beginIndex==0&&endIndex==0){
printPath();
}
}
p[i].inPath = false;
}
}
}
if(isLast){
p[beginIndex].nextIndex = endIndex;
return dis[beginIndex][endIndex];
}
return result;
}
void printPath(){
int pre = 0,next;
int count = MAX;
while(count--){
next = p[pre].nextIndex;
printf("%d->%d ",pre,next);
pre = next;
}
printf("\n");
}
int main(int argc, char* argv[])
{
//freopen("i://out.txt","w",stdout);
p[0].inPath = true;
printf("%d\n",tsp(0,0));
return 0;
}
转载于:https://www.cnblogs.com/yangyh/archive/2011/10/08/2202995.html