您的位置:首页 > 其它

求马跳棋盘踏满5*5的国际象棋棋盘有多少种解法?

2017-03-05 11:57 363 查看


题目如图所示。

#include<iostream>
#include<cstdio>
#define D 8
#define N 5
using namespace std;

int chessboard

;
int chessboard_copy

;
int step[N*N+1];
int step_num=0, result=0, flag=1;
static int dx[D]={-2, -1, 1, 2, 2, 1, -1, -2};
static int dy[D]={1, 2, 2, 1, -1, -2, -2, -1};

void show01()
{
cout<<"按5*5棋盘格式输出:"<<endl;
int i, j;
for(i=0; i<N; ++i)
{
for(j=0; j<N; ++j)
printf("%-2d ", chessboard[i][j]);
cout<<endl;
}
cout<<endl;
}

void show()
{
cout<<"按题目要求输出:"<<endl;
int i;
cout<<"{ ";
for(i=1; i<=N*N; ++i)
printf("[%d,%d] ", i, step[i]);
cout<<" }"<<endl<<endl;
}

void horse(int x, int y)
{
if(x>=0 && x<N && y>=0 && y<N && chessboard[x][y]==0)
{
//为了按题目输出,step_num是第几步,chessboard_copy[x][y]是棋盘标号
step[++step_num] = chessboard_copy[x][y];
//标记棋盘被访问
chessboard[x][y] = step_num;
if(step_num == N*N)
{
if(flag)
{
show01();
show();
}
//题目要求只输出一个解
flag = 0;
result++;
}
int i;
for(i=0; i<D; ++i)
{
horse(x+dx[i], y+dy[i]);
}
//回溯
chessboard[x][y] = 0;
--step_num;
}

}

int main()
{
int i, j;
//初始化棋盘副本的编号
for(i=0; i<N; ++i)
for(j=0; j<N; ++j)
chessboard_copy[i][j] = i*N+j+1;

horse(0, 0);
cout<<"总共解的种数为:"<<result<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐