在半个中国象棋棋盘上,马在左下角(1,1)处,马走日字,求到指定位置有多少种走法


在半个中国象棋棋盘上,马在左下角(1,1)处,马走日字…而且只能往右走…不能向左…可上可下…求从起点到(m, n)处有几种不同的走法。
分析:
半个中国象棋棋盘可用二维数组来表示:static int chessboard[5][9];
能走的方向用数组来表示:
const int dx[4] = {2, 1, -1, -2};
const int dy[4] = {1, 2, 2, 1};


#include<iostream>

using namespace std;

static int chessboard[5][9];
static int count=0;
/*
马走日的方向,(dx, dy),dx表示5行中的第几行的竖直方向,dy表示9列中第几列的横方向。
上:(2, 1)
上右:(1, 2)
下右:(-1, 2)
下: (-2, 1)
*/
const int dx[4] = {2, 1, -1, -2};
const int dy[4] = {1, 2, 2, 1};

void horse_count(int srcx, int srcy, int destx, int desty)
{
    if(srcx>=0 && srcx<5 && srcy>=0 && srcy<9 && chessboard[srcx][srcy]==0)
    {
        if(srcx == destx-1 && srcy == desty-1)
        {
            count++;
            return;
        }
        //标记为已经走过
        chessboard[srcx][srcy] = 1;
        int i;
        for(i=0; i<4; ++i)
        {
            horse_count(srcx+dx[i], srcy+dy[i], destx, desty);
        }
        //当走完四个方向后,回溯到之前走过的一步,标记为未走过。
        chessboard[srcx][srcy] = 0;
    }
}

int main()
{
    cout<<"请输入要到达棋盘的坐标: ";
    int m, n;
    cin>>m>>n;
    horse_count(0, 0, m, n);
    cout<<"走法的种数:"<<count<<endl;
    return 0;
}
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值