您的位置:首页 > 编程语言 > C语言/C++

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

2017-02-26 21:23 344 查看
在半个中国象棋棋盘上,马在左下角(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c-c++
相关文章推荐