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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP