旅行者问题

基本数据结构省略了,用队列存储状态,即还剩下哪些点没有访问过.然后采取回溯算法进行遍历.

#include "stdafx.h"
#include "队列ADT.h"
#include "math.h"
#include "string.h"
#define N 4
#define Number (1<<N) -1
#define Infinity 1000
int AllDistance[N][Number] = {0};
int CurrentPath[N][Number];
int Find(int start,int Current,int Num,queue NodeCollection,int C[][N])
{
    int Count = 0;
    int Nextnode;
    int Distance = Infinity,NextDistance;
    if(NodeCollection->size == 0)//如果点集为空
    {
        CurrentPath[Current][Num] = start;
        return C[Current][start];
    }
    else
    {
        while(Count++!=NodeCollection->size)//遍历队列中所有点
        {
             Nextnode = Dequeue(NodeCollection);//从队列中取出一点作为下个目的点
            if(AllDistance[Nextnode][Num-(1<<Nextnode)]!=0&&NodeCollection->size!=1)
         NextDistance = AllDistance[Nextnode][Num-(1<<Nextnode)];//已经计算过相关数据,不用递归
             else//没有相关数据
             NextDistance = Find(start,Nextnode,Num-(1<<Nextnode),NodeCollection,C);
             Enqueue(NodeCollection,Nextnode);
             if(C[Current][Nextnode] + NextDistance < Distance)
             {
                 Distance = C[Current][Nextnode] + NextDistance;//将最短路径更新
                 AllDistance[Current][Num] = Distance;//将相关记录记录
                 CurrentPath[Current][Num] = Nextnode; //记录路径
             }
        }
        return Distance;
    }
}
void ReadNodeintoQueue(queue Q)
{
    for(int i = 0;i<=N-1;i++)
        Enqueue(Q,i);
}
int FindMin(int C[][N])
{
    int start,Minstart;
    int Distance,MinDistance = Infinity;
    queue Q = (queue)malloc(sizeof(Queue));
    Initialize(Q,N);
    ReadNodeintoQueue(Q);

    for(int i = 0;i<=N-1;i++)//选择一个起始点
    {

        start = Dequeue(Q);
        Distance = Find(start,start,Number-(1<<start),Q,C);
        Enqueue(Q,i);
        printf("%d: %d\n",i,Distance);
        if(Distance < MinDistance)
        {
            Minstart = start;
            MinDistance = Distance;
        }
    }
    return MinDistance;
}

int _tmain(int argc, _TCHAR* argv[])
{

    int x = (1<<4);
    queue Q = (queue)malloc(sizeof(Queue));
    Initialize(Q,5);
    int MinDistance;
    int C[N][N];
    for (int i = 0;i<=N-1;i++)
    {
        for(int j = 0;j<=N-1;j++)
        {
            if(i == j)
                C[i][j] = 0;
            else
                C[i][j] = Infinity;
        }
    }
    C[0][1] = 1;
    C[0][2] =1;
    C[1][0] = 1;
    C[1][2] = 2;
    C[1][3] = 7;
    C[2][0] = 1;
    C[2][3] = 9;
    C[3][0] = 4;
    C[3][2] = 9;
    MinDistance = FindMin(C);
    return 0;
}

你可能感兴趣的:(旅行者问题)