您的位置:首页 > 其它

读书-算法《程序设计导引及在线实践》-简单计算题2:棋盘上的距离

2014-06-01 18:57 316 查看
题目:棋盘上的距离

求国际象棋中王、后、车、象从起始位置到目标位置所需的最少步骤。



 

行走规则如下:

王:横、竖、斜都可以走,但每步只能走一格。

后:横、竖、斜都可以走,但每步格数不限。

车:横、竖都可以走,不能斜着走,每步格数不限。

象:只能斜着走,格数不限。

 

我没有下过国际象棋,但题目中这四种角色的行走规则。把题目翻译一下,在一个8*8 的矩阵里面,按照给定的规则从一个点到另一个点的最近路径,好像也不用翻译,题目就是这么说的。

 

代码实现如下:
#include <stdio.h>
#include <math.h>

void main()
{
int ncase, i;
scanf("%d",&ncase);

for(i = 0; i < ncase; i++)
{
char begin[3], end[3];/*这里定义为3,考虑到了还要存入字符串结束符'\0'*/
int x, y;
scanf("%s %s",begin, end);

x = abs(begin[0] - end[0]);
y = abs(begin[1] - end[1]);

if (0 == x && 0 == y)
{
printf("0 0 0 0\n");
}
else
{
/*steps of king*/
if (x < y)
{
printf("%d ", y);
}
else
{
printf("%d ", x);
}

/*steps of queen*/
if (x == y || 0 == x || 0 == y)
{
printf("1 ");
}
else
{
printf("2 ");
}

/*steps of rook*/
if (0 == x || 0 == y)
{
printf("1 ");
}
else
{
printf("2 ");
}

/*steps of bishop*/
if (abs(x-y)%2 != 0)
{
printf("Inf\n");
}
else if(x == y)
{
printf("1\n");
}
else
{
printf("2\n");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: