C++程序:找出二维平面中从一个点到另一个点的移动路径
假设在二维平面中有两个点a和b,它们的坐标分别为(x1, y1)和(x2, y2)。目前我们位于点'a',并且每次只能垂直或水平移动一个单位距离。我们需要从点'a'移动到点'b',再返回点'a',最后再次移动到点'b'。除了点a和b之外,不允许经过相同的点多次。我们需要找出整个行程中所做的移动,并输出结果。如果向右移动,则输出'R',向左移动则输出'L',向上移动则输出'U',向下移动则输出'D'。需要注意的是,x2 > x1 且 y2 > y1。
例如,如果输入x1 = 0,y1 = 1,x2 = 3,y2 = 4,则输出将为UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU
为了解决这个问题,我们将遵循以下步骤:
s := a blank string for initialize i := 0, when i < y2 - y1, update (increase i by 1), do: add "U" at the end of s for initialize i := 0, when i < x2 - x1, update (increase i by 1), do: add "R" at the end of s for initialize i := 0, when i < y2 - y1, update (increase i by 1), do: add "D" at the end of s for initialize i := 0, when i < x2 - x1, update (increase i by 1), do: add "L" at the end of s add "LU" at the end of s for initialize i := 0, when i < y2 - y1, update (increase i by 1), do: add "U" at the end of s for initialize i := 0, when i < x2 - x1, update (increase i by 1), do: add "R" at the end of s add "RD" at the end of s add "RD" at the end of s for initialize i := 0, when i < y2 - y1, update (increase i by 1), do: add "D" at the end of s for initialize i := 0, when i < x2 - x1, update (increase i by 1), do: add "L" at the end of s add "LU" at the end of s return s
示例
让我们来看下面的实现,以便更好地理解:
#include <bits/stdc++.h> using namespace std; string solve(int x1, int y1, int x2, int y2){ string s = ""; for(int i = 0; i < y2 - y1; i++) s.append("U"); for(int i = 0; i < x2 - x1; i++) s.append("R"); for(int i = 0; i < y2 - y1; i++) s.append("D"); for(int i = 0; i < x2 - x1; i++) s.append("L"); s.append("LU"); for(int i = 0; i < y2 - y1; i++) s.append("U"); for(int i = 0; i < x2 - x1; i++) s.append("R"); s.append("RD"); s.append("RD"); for(int i = 0; i < y2 - y1; i++) s.append("D"); for(int i = 0; i < x2 - x1; i++) s.append("L"); s.append("LU"); return s; } int main() { int x1 = 0, y1 = 1, x2 = 3, y2 = 4; cout<< solve(x1, y1, x2, y2); return 0; }
输入
0, 1, 3, 4
输出
UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU
广告