Thursday, October 7, 2010

Travelling sales man problem in C Programming

ALGORITHM
C Programming - Travelling sales man problem solving using Back Tracking


#include
#include
#include

#define MAX 10

struct Tour
{
int iCount;
int aiCity[MAX];
}cTour;

void fnDisplay(int cCity,int iN)
{
int iI;
static int count;
cTour.aiCity[cTour.iCount]=0;
printf("\nSOLUTION:%d\n",count++);
printf("\nPath is : \n");
for(iI=0;iI<=cTour.iCount;iI++)
printf(" %d ",cTour.aiCity[iI]);
}

int fnVisited(int adj)
{
int iI;
for(iI=0;iI
if(cTour.aiCity[iI]==adj)
return 1;
return 0;
}

int fnPromising(int cCity,int adj,int aiAdj[MAX][MAX])
{
if(!fnVisited(adj) && aiAdj[cCity][adj]!=0)
return 1;
return 0;
}

void fnSearch(int cCity,int iN,int aiAdj[MAX][MAX])
{
int adj;
cTour.aiCity[cTour.iCount++]=cCity;
if(cTour.iCount==iN && aiAdj[cCity][0]!=0)
{
fnDisplay(cCity,iN);
getch();
}
else
for(adj=0;adj
{
if(fnPromising(cCity,adj,aiAdj))
{
fnSearch(adj,iN,aiAdj);
}
}
cTour.aiCity[cTour.iCount]=-1;
cTour.iCount-=1;
}

void main()
{
int iN,iI,aiAdj[MAX][MAX],iJ;
clrscr();
cTour.iCount=0;
printf("\nEnter the no of cities : ");
scanf("%d",&iN);
printf("\nEnter the adjency matrix : \n");
for(iI=0;iI
for(iJ=0;iJ
scanf("%d",&aiAdj[iI][iJ]);
for(iI=0;iI
cTour.aiCity[iI]=-1;
fnSearch(0,iN,aiAdj);
getch();
}

/*
OUTPUT:

Enter the no of cities : 4

Enter the adjency matrix :
0 1 0 1
1 0 1 1
0 1 0 1
1 1 1 0

SOLUTION:0

Path is :
0 1 2 3 0
SOLUTION:1

Path is :
0 3 2 1 0

*/


No comments:

Post a Comment