马踏棋盘C语言实现

该代码为未优化算法实现,8*8棋盘,挑选效率高的起始点(2,0),以及效率高的走法

每一次走法的尝试都是回溯法,一条路走到黑,直到行不通,再重新开始


////////////////回溯法+递归//////////////图的深度优先遍历///////////////////////////////
#include 
//#include 
#include 

#define X 8
#define Y 8

int chess[X][Y];

/*int nextxy(int *x,int *y,int count)
{
	switch(count)
	{
	case 0:
		if(*x+2=0 && chess[*x+2][*y-1]==0)
		{
			*x+=2;
			*y-=1;
			return 1;
		}
		break;
	case 2:
		if(*x+1=0 && chess[*x+1][*y-2]==0)
		{
			*x+=1;
			*y-=2;
			return 1;
		}
		break;
	case 3:
		if(*x-1>=0 && *y-2>=0 && chess[*x-1][*y-2]==0)
		{
			*x-=1;
			*y-=2;
			return 1;
		}
		break;
	case 4:
		if(*x-2>=0 && *y-1>=0 && chess[*x-2][*y-1]==0)
		{
			*x-=2;
			*y-=1;
			return 1;
		}
		break;
	case 5:
		if(*x-2>=0 && *y+1=0 && *y+2=0 && chess[*x+2][*y-1]==0)
		{
			*x+=2;
			*y-=1;
			return 1;
		}
		break;
	case 1:
		if(*x+2=0 && chess[*x+1][*y-2]==0)
		{
			*x+=1;
			*y-=2;
			return 1;
		}
		break;
	case 3:
		if(*x+1=0 && *y-1>=0 && chess[*x-2][*y-1]==0)
		{
			*x-=2;
			*y-=1;
			return 1;
		}
		break;
	case 5:
		if(*x-2>=0 && *y+1=0 && *y-2>=0 && chess[*x-1][*y-2]==0)
		{
			*x-=1;
			*y-=2;
			return 1;
		}
		break;
	case 7:
		if(*x-1>=0 && *y+2count=0;  // 对现在的位置,每次从位置0出开始走
	chess[x][y]=tag;
	if(tag==X*Y)
	{
		print();//打印棋盘
		return 1;
	}
	//确定成功走出第一步
	flag=nextxy(&x1,&y1,count);
	while(flag==0 && count<=7)
	{
		++count;  // 若行不通,则切换走的方向
		flag=nextxy(&x1,&y1,count);
	}
	while(flag)
	{
		 if(TravelChessBoard(x1,y1,tag+1))  // 成功走完全部
			 return 1;
		 // 未成功走完,换个方向重新开始走
		 x1=x;y1=y;
		 ++count;
		 flag=nextxy(&x1,&y1,count);
	     while(flag==0 && count<7)
	     {
		     ++count;
		     flag=nextxy(&x1,&y1,count);
	     }
	}
	if(flag==0)
	{
		chess[x][y]=0;
	}
	return 0;
}

int main()
{
	int i,j;
	clock_t start,finish;
	start=clock();
	for(i=0;i



马踏棋盘C语言实现_第1张图片

你可能感兴趣的:(数据结构与算法分析)