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

这里写图片描述

题目如图所示。

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

int chessboard[N][N];
int chessboard_copy[N][N];
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值