马踏棋盘递归所有解

                  这次马踏棋盘是用递归实现的,而且可以弄出来所有解,当时电脑跑的最快的都有40多万解了,这个也可以看你电脑cpu好坏,一般超级本跑不动。这是实际上和八皇后是同一种性质的问题,都用到了回溯的思想,有接进行下一个,不行了退回去,在进行尝试。不多说了,直接上代码;

    

#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
#define N 8
int cnt=1;     // 记录马的位置
int n=1;
int chess[8][8]={0};  //棋盘
int move[8][2]={ 
	{1,-2},{2,-1},
	{2,1},{1,2},
	{-1,2},{-2,1},
	{-2,-1},{-1,-2}
	}; 
void horse(int ,int );
void printhorse();

int main()           //主函数
{
	chess[0][0]=1;
	horse(0,0);
	return 0;
}
void horse(int x,int y)   //执行过程
{
	int i;
	int a,b;
	for(i=0;i<N;i++)
	{
		a=x+move[i][0];
		b=y+move[i][1];
		if(a>=0&&a<N&&b>=0&&b<N&&!chess[a][b])
		{
			 chess[a][b]=++cnt;
			if(cnt<64)
			{	horse(a,b); 
			
			}                     // 递归
			else{
				printhorse();
			//	exit(0);

				
			}    
				chess[a][b]=0;//修改ab的值归为0
				cnt--;
		}
	}
}
void printhorse()          //输出马踏棋盘
{
	int i,j;
	printf("输出第%d组解:\n",n++);
    for(i=0;i<N;i++)
	{
		for(j=0;j<N;j++)
			printf("%3d ",chess[i][j]);
	printf("\n");
	}
}

  

 演示结果

    《马踏棋盘递归所有解》   


    

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/lotluck/article/details/43153805
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞