Computer >> Máy Tính >  >> Lập trình >> C ++

Chương trình C ++ để tìm ra các bước di chuyển để đọc một điểm từ một điểm khác trong mặt phẳng 2D

Giả sử có hai điểm trên mặt phẳng 2D a và b có tọa độ lần lượt là (x1, y1) và (x2, y2). Hiện tại, chúng ta đang ở điểm 'a' và chúng ta có thể di chuyển với khoảng cách 1 theo chiều dọc hoặc chiều ngang. Chúng ta di chuyển đến điểm b từ điểm a, sau đó quay lại điểm a, và chúng ta lại đến điểm b. Không được phép di chuyển qua các điểm giống nhau nhiều hơn một lần trừ điểm a và b. Chúng tôi phải tìm ra những động thái mà chúng tôi sẽ thực hiện trong toàn bộ chuyến đi này và xuất ra nó. Nếu chúng ta di chuyển sang phải, chúng ta in "R", "L" nếu chúng ta di chuyển sang trái, "U" nếu chúng ta di chuyển lên và "D" nếu chúng ta di chuyển xuống. Một điều chúng ta cần lưu ý là x2> x1 và y2> y1.

Vì vậy, nếu đầu vào là x1 =0, y1 =1, x2 =3, y2 =4, thì đầu ra sẽ là UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU

Để giải quyết vấn đề này, chúng tôi sẽ làm theo các bước sau -

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

Ví dụ

Hãy cùng chúng tôi xem cách triển khai sau để hiểu rõ hơn -

#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;
}

Đầu vào

0, 1, 3, 4

Đầu ra

UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU