#define X 5即可测试任何阶马踏棋盘游戏,阶数越高,程序运行时间将会越长。(8阶都不知道要跑到什么时候。。)
void CHorse::funcStart()
{
funcTravel(0, 0, nStep);
}#include <stdio.h>
#include <iostream>
#define X 5
using namespace std;
static int nChess[X][X] = {0};
class CHorse
{
public:
CHorse(); // 构造函数
void funcStart(); // 开始行走
void funcCout(); // 打印棋盘
void funcTravel(int x, int y, int n); // 从点<x,y>继续行走
bool funcNextStep(int *x, int *y, int z); // 寻找下一步可行点
int funcGetnCount(); // 获取nCount
private:
static int nCount; // 统计总共的可行方案数
};
int CHorse::nCount = 0;
CHorse::CHorse()
{
}
int CHorse::funcGetnCount()
{
return nCount;
}
void CHorse::funcStart()
{
funcTravel(0, 0, 1);
}
void CHorse::funcTravel(int x, int y, int n)
{
int nTraveli, nX1=x, nY1=y;
nChess[x][y] = n;
if( n==X*X )
{
// 棋盘遍历完毕
funcCout();
}
else
{
// 循环遍历周边8个可行方案
for(nTraveli=0; nTraveli<8; nTraveli++)
{
if( funcNextStep(&nX1, &nY1, nTraveli) )
{
funcTravel(nX1, nY1, n+1);
nChess[nX1][nY1] = 0;
nX1 = x;
nY1 = y;
}
}
}
}
bool CHorse::funcNextStep(int *x, int *y, int z)
{
switch(z)
{
case 0:
if( *x>1 && *y>0 && nChess[*x-2][*y-1]==0 )
{
*x = *x-2;
*y = *y-1;
return true;
}
break;
case 1:
if( *x<X-2 && *y>0 && nChess[*x+2][*y-1]==0 )
{
*x = *x+2;
*y = *y-1;
return true;
}
break;
case 2:
if( *x>1 && *y<X-1 && nChess[*x-2][*y+1]==0 )
{
*x = *x-2;
*y = *y+1;
return true;
}
break;
case 3:
if( *x<X-2 && *y<X-1 && nChess[*x+2][*y+1]==0 )
{
*x = *x+2;
*y = *y+1;
return true;
}
break;
case 4:
if( *x>0 && *y>1 && nChess[*x-1][*y-2]==0 )
{
*x = *x-1;
*y = *y-2;
return true;
}
break;
case 5:
if( *x<X-1 && *y>1 && nChess[*x+1][*y-2]==0 )
{
*x = *x+1;
*y = *y-2;
return true;
}
break;
case 6:
if( *x>0 && *y<X-2 && nChess[*x-1][*y+2]==0 )
{
*x = *x-1;
*y = *y+2;
return true;
}
break;
case 7:
if( *x<X-1 && *y<X-2 && nChess[*x+1][*y+2]==0 )
{
*x = *x+1;
*y = *y+2;
return true;
}
break;
}
return false;
}
void CHorse::funcCout()
{
int i, j;
nCount++;
for(i=0; i<X; i++)
{
for(j=0; j<X; j++)
{
printf("%-4d", nChess[i][j]);
}
printf("\n");
}
printf("\n\n");
}
void main()
{
int n;
CHorse objHorse;
objHorse.funcStart();
printf("::马踏棋盘游戏::以<0,0>为起点的5阶棋盘共有%d种走法\n\n", objHorse.funcGetnCount());
}原文地址:http://blog.csdn.net/bigric3/article/details/44937923