跳马问题

来源:互联网 发布:linux tftpd 编辑:程序博客网 时间:2024/05/22 03:14
跳马问题主要思路:
         1,马只能向八个方向跳,题目规定只能向右走,就只剩下四个方向了。
          2,题目应用队列解决,而队列可以用循环数组表示。
          3,每一次走到目标位置,应用计数变量加一;

【问题描述】

    有一只中国象棋中的 " 马 ” ,在半张棋盘的左上角出发,向右下角跳去。规定只许向右跳(可上,可下, 但不允许向左跳)。请编程求从起点 A(1,1) 到终点 B(m,n) 共有多少种不同跳法。

【输入格式】
输入文件只有一行,两个整数m和n(1<=m,n<=20),两个数之间有一个空格。
【输出格式】
输出文件只有一个整数,即从 A 到 B 全部的走法。
【输入输出样例】
输入数据:
5 9
输出数据:
37
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int  dtr[4][2]={{-2,1},{2,1},{1,2},{-1,2}};
int n, m, num=0;
struct state
{
short x;
short y;
}sp[10000000];//建立队列; //
struct state now;
struct state next;
int bfs(int a, int b)
{

int start=0, end=1;
sp[start].x=a;
sp[start].y=b;
while(start<end)
{
now.x=sp[start].x;
now.y=sp[start].y;// 将队头元素赋给now// 
start++;
if(now.x==n&&now.y==m) 
{
num++;//满足条件,计数变量加一// 
}
for(int i=0;i<4;i++)
{
next.x=now.x+dtr[i][0];
next.y=now.y+dtr[i][1];
if(next.x>=1&&next.y>=1&&next.x<=n&&next.y<=m)
{
sp[end]=next;//满足条件,进入队列// 
end++;
}
}
}
return num;
}


int main()
{
scanf("%d %d",&n,&m);//输入目标位置// 
int k=bfs(1,1);//计算步数// 
printf("%d\n",k);//输出结果// 
return 0;

}






原创粉丝点击