您的位置:首页 > 理论基础 > 数据结构算法

codeforces-3A-Shortest path of the king( 棋盘最短路径 + 贪心 )

2016-06-03 15:48 573 查看
A. Shortest path of the kingtime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t.As the king is not in habit of wasting his time, he wants to get from his current position s to square t inthe least number of moves. Help him to do this.In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).InputThe first line contains the chessboard coordinates of square s, the second line — of square t.Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h),the second one is a digit from 1to 8.OutputIn the first line print n — minimum number of the king's moves. Then in n linesprint the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.L, R, U, D standrespectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.Examplesinput
a8
h1
output
7
RD
RD
RD
RD
RD
RD
RD
题目的大意是,给定一个国王的起点和终点,求国王从起点到终点的最短路径。(国王每次只能移动到周围的8个格子之一)
这题其实很简单.....横向长度和纵向长度都是确定的,主要刚开始看这道题的时候,看到国王可以斜着走于是想复杂,其实不管
国王是左上方斜走,右上斜走,左下斜走,右下斜走,有两点是唯一不变的,
(1)斜着走必定会在x方向改变1,y方向改变1。
(2)四个斜着走的方向在每次测试用例中只会出现一种。
(就是比如终点在右下方,国王在斜着走的步骤就只会选择右下了,如果不是唯一,则肯定不是最短路径!)
然后下面的代码就很容易理解了.
#include<cstdio>char a[3],b[3],c,d,x,y;int main(){gets(a);						//读取国王起点    		a8gets(b);						//读取国王终点    		h1x=a[0]-b[0];					//求出横向位移    		a-h = -7y=a[1]-b[1];					//求出纵向位移    		8-1 = 7c=((x<0)?x=-x,'R':'L');				//横向位移如果小于0,转为正数,说明往右边移动'R',否则往左边移动'L'd=((y<0)?y=-y,'U':'D');				//纵向位移如果小于0,转为正数,说明往上方移动'U',否则往下方移动'D'printf("%d",x>y?x:y);				//x,y哪个绝对值大,哪个就是步数while(x|y){						//x或者y存在则还有步数没走完puts("");if(x)x--,putchar(c);			        //输出横向位移if(y)y--,putchar(d);			        //输出纵向位移}return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息