Shortest path of the king

Problem

  The 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 in the 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).

 

Input

  The 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 1 to 8.

 

Output

  In the first line print n — minimum number of the king's moves. Then in n lines print 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 stand respectively 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.

 

Examples
  input
    a8
    h1
  output
    7
    RD
    RD
    RD
    RD
    RD
    RD
    RD

 

 

 
题目大意
  国际象棋中,国王每步可以走到与其相邻的八个格子中。给出当前国王的位置与目标位置,求最短操作序列。

 

算法

  将坐标相减得到dx和dy,通过正负判断起点终点的相对位置,确定国王走的方向xStep(“R”或“L”)和yStep(“U”或“D”)并将dx和dy取绝对值。

  答案:

    n = max{dx, dy}

  路径:

    (dx – dy) * xStep  (dx > dy)

    (dy - dx) * yStep  (dx < dy)

    min{dx, dy} * (xStep + yStep)  

  时间复杂度:

    O(n)

  空间复杂度:

    O(n)

 
代码
 1 s = input()
 2 t = input()
 3 
 4 x = ord(s[0]) - ord(t[0])
 5 y = ord(s[1]) - ord(t[1])
 6 
 7 if (x < 0):
 8     xStep = "R"
 9     x = -x
10 else:
11     xStep = "L"
12 if (y < 0):
13     yStep = "U"
14     y = -y
15 else:
16     yStep = "D"
17 
18 print(max(x, y))
19 while (x > y):
20     print(xStep)
21     x -= 1
22 while (x < y):
23     print(yStep)
24     y -= 1
25 while (x):
26     print(xStep + yStep)
27     x -= 1
posted @ 2018-06-19 02:10  Efve  阅读(212)  评论(0编辑  收藏  举报