读书-算法《程序设计导引及在线实践》-简单计算题2:棋盘上的距离
2014-06-01 18:57
316 查看
题目:棋盘上的距离
求国际象棋中王、后、车、象从起始位置到目标位置所需的最少步骤。
行走规则如下:
王:横、竖、斜都可以走,但每步只能走一格。
后:横、竖、斜都可以走,但每步格数不限。
车:横、竖都可以走,不能斜着走,每步格数不限。
象:只能斜着走,格数不限。
我没有下过国际象棋,但题目中这四种角色的行走规则。把题目翻译一下,在一个8*8 的矩阵里面,按照给定的规则从一个点到另一个点的最近路径,好像也不用翻译,题目就是这么说的。
代码实现如下:
求国际象棋中王、后、车、象从起始位置到目标位置所需的最少步骤。
行走规则如下:
王:横、竖、斜都可以走,但每步只能走一格。
后:横、竖、斜都可以走,但每步格数不限。
车:横、竖都可以走,不能斜着走,每步格数不限。
象:只能斜着走,格数不限。
我没有下过国际象棋,但题目中这四种角色的行走规则。把题目翻译一下,在一个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"); } } } }
相关文章推荐
- 读书-算法《程序设计导引及在线实践》-简单计算题3:校门外的树
- 读书-算法《程序设计导引及在线实践》-简单计算题5:装箱问题
- 读书-算法《程序设计导引及在线实践》-简单计算题1:鸡兔同笼
- 读书-算法《程序设计导引及在线实践》-简单计算题4:填词
- ACM简单计算题-棋盘上的距离
- 简单计算题:棋盘上的距离
- 【算法解题报告】棋盘上的距离&校门外的树
- 计算编辑距离的算法
- java实现编辑距离算法,计算字符串相似度
- 随机计算TFIDF作为权重,然后利用余弦距离进行聚类,用的是简单k-means算法。
- 算法习题23:用最简单, 最快速的方法计算出下面这个圆形是否和正方形相交
- 一天一个算法题-简单的-递归-计算a+aa+aaa+...+aaaa...a的数值
- 一天一个算法题-简单的-递归-计算球的落下
- 一个简单的JavaScript 日期计算算法
- HDU 4617 Weapon (简单三维计算几何,异面直线距离)
- [算法]计算编辑距离
- 计算GPS WGS_84 两点的距离 更加细腻的算法
- 简单算法系列之完数的计算
- 一个简单的计算素数的算法
- 使用欧几里德距离构建简单的推荐系统计算用户相似度