马踏棋盘算法(骑士周游问题)C++

#include<iostream>
#include<cstdio>
using namespace std;

#define X 8  //定义棋盘
#define Y 8
int chess[X+1][Y+1]; 

int nextxy(int &x,int &y,int count){ //判断该棋盘格是否可以插入棋子 
	switch (count)
	{
		case 1:
			if(x + 2 <= X && y - 1 >= 1 && chess[x+2][y-1] == 0){
				x += 2;
				y -= 1;
				return 1;
			};break;
		case 2:
			if(x + 2 <= X && y + 1 <= Y && chess[x+2][y+1] == 0){
				x += 2;
				y += 1;
				return 1;
			};break;
		case 3:
			if(x + 1 <= X && y - 2 >= 1 && chess[x+1][y-2] == 0){
				x += 1;
				y -= 2;
				return 1;
			};break;
		case 4:
			if(x + 1 <= X && y + 2 <= Y && chess[x+1][y+2] == 0){
				x += 1;
				y += 2;
				return 1;
			};break;
		case 5:
			if(x - 2 >= 1 && y - 1>= 1 && chess[x-2][y-1] == 0)
			{
				x -= 2;
				y -= 1;
				return 1;
			};break;
		case 6:
			if(x - 1 >= 1 && y - 2 >= 1 && chess[x-1][y-2] == 0)
			{
				x -= 1;
				y -= 2;
				return 1;
			};break;
		case 7:
			if(x - 1 >= 1 && y + 2 <= Y && chess[x-1][y+2] == 0)
			{
				x -= 1;
				y += 2;
				return 1;
			};break;
		case 8:
			if(x - 2 >= 1 && y + 1 <= Y && chess[x-2][y+1] == 0)
			{
				x -= 2;
				y += 1;
				return 1;
			};break;
		default :
			break;
	}
	return 0;
} 
void print()
{	
	for(int i = 1;i <= X; i++ )
	{
		for(int j = 1; j <= Y; j++ )
		{
			printf("%2d\t", chess[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}
/*
深度优先遍历棋盘 
*/ 
int TravelChessBoard(int x,int y,int tag){
	int x1 = x,y1 = y,flag = 0,count = 0;
	chess[x][y] = tag;
	
	if(tag == X * Y)//若踏满棋盘则返回 
	{
		print();
		return 1;
	}
	flag = nextxy(x,y,count);
	while(flag == 0 && count <= 8){   //首先找到第一个合理的位置 
		count++;
		flag = nextxy(x1,y1,count);
	}
	while(flag){ 
		if(TravelChessBoard(x1,y1,tag+1))return 1; //递归进行探索路径 
		
		//若未探索到合适路径,则弹回(隐藏条件调用进去的递归函数返回值为0) 
		x1 = x; //重新探索,依然从该点进行只是count发生了自增 
		y1 = y;
		count++;
		
		//重复递归 
		flag = nextxy(x1,y1,count);
		while(flag == 0 && count <= 8){   
		count++;
		flag = nextxy(x1,y1,count);
	}
		
	}
	//最终仍然探索不到路径则返回上一层,且改位置赋值为0 
	if(flag == 0)chess[x][y] = 0;
	return 0;
	
}
int main(){
	
	for(int i = 1;i <= X; i++ )
	{
		for(int j = 1;j <= Y; j++ )
		{
			chess[i][j] = 0;
		}
	}

	if( !TravelChessBoard(3, 1, 1) )
	{
		printf("马踏棋盘失败~\n");
	}
}



猜你喜欢

转载自blog.csdn.net/peachhhh/article/details/108329734