骑士周游问题-回溯法

天啊,这个问题简直有毒,超级有毒!!!!有木有,可以试试。。。。不相信的话

以前玩单片机时候就有这么一种问题:同一个程序,不同的执行效果,这么坑!!!

劝大家规范起见,switch()下别他喵的有了return就不要break了,简直天壤之别!!!

//骑士周游问题
#include <time.h>
#include <iostream>
using namespace std;
const int X=8,Y=8;
int chess[X][Y];
void print()
{
	for(int i=0;i<Y;i++)
	{
		for(int j=0;j<X;j++)
		{
			printf("%-3d",chess[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}
bool nextxy(int &x,int &y,int count)
{
    switch(count)
	{
	case 0:
		if(x+1 < X && y-2 >= 0 && !chess[x+1][y-2])
		{
			x  = x+1, y = y-2;
			return true;
		}
		break;
	case 1:
		if(x+2 < X && y-1 >= 0 && !chess[x+2][y-1])
		{
			x = x+2, y = y-1;
			return true;
		}
		break;
	case 2:
		if(x+2 < X && y+1 < Y  && !chess[x+2][y+1])
		{
			x = x+2, y = y+1;
			return true;
		}
		break;
	case 3:
		if(x+1 < X && y+2 < Y && !chess[x+1][y+2])
		{
			x = x+1, y = y+2;
			return true;
		}
		break;
	case 4:
		if(x-1 >= 0 && y+2 < Y && !chess[x-1][y+2])
		{
			x = x-1, y = y+2;
			return true;
		}
		break;
	case 5:
		if(x-2 >= 0 && y+1 < Y && !chess[x-2][y+1])
		{
			x = x-2, y =y+1;
			return true;
		}
		break;
	case 6:
		if(x-2 >= 0 && y-1 >= 0 && !chess[x-2][y-1])
		{
			x = x-2, y = y-1;
			return true;
		}
		break;

	case 7:
		if(x-1 >= 0 && y-2 >= 0 && !chess[x-1][y-2])
		{
			x = x-1, y = y-2;
			return true;
		}
		break;
	default :
		break;
    }
return false;
}
bool knight_tour(int x,int y,int tag=1)//坐标和步数
{
	int count=0;
	bool flag=false;

	int x1,y1;
	chess[x][y]=tag;
	if(tag==X*Y)//说明走完了
	{
		print();
		return true;
	}
	while(count<8)//应该是表示有几种选择
	{
		flag=false;
		x1=x;
		y1=y;
		while(!flag&&count<8)
		{
			flag=nextxy(x1,y1,count++);
		}
		if(flag&&knight_tour(x1,y1,tag+1))
			return true;

	}
	if(count==8)
	{
		chess[x][y]=0;
		return false;
	}

}
void main()
{
	int x,y;
	memset(chess,0,sizeof(chess));
	clock_t  start,end;
	cout<<"请输入棋子坐标:"<<endl;
	cin>>x>>y;
	start=clock();

	if(!knight_tour(x,y))
		printf("Error!!");
	end=clock();
	printf("\n");
	printf("%.3f S\n",(double)(end-start)/CLOCKS_PER_SEC);
	
}

还有这个程序,我他喵的电脑完全算不出来复杂的。。。。

输入4,4

完全木反应

好吧,吸取经验,输入0,0

最后还是说一下程序时间计算问题,以前博客谈过一次clock()/CLOCKS_PER_SEC,直接这样做不太准

还是按照上面程序里面使用的,clock_t型一个start,一个end,相减后使用,头文件time.h或者ctime

猜你喜欢

转载自blog.csdn.net/shuiyihang0981/article/details/82714583