สมมติว่าเรามีชุดคำสั่งเป็นสตริง สตริงจะมีตัวอักษรสี่ตัวที่แตกต่างกันสำหรับสี่ทิศทาง U สำหรับขึ้น D สำหรับลง L สำหรับซ้ายและ R สำหรับขวา นอกจากนี้เรายังมีตำแหน่งเซลล์เริ่มต้น (x, y) ค้นหาตำแหน่งเซลล์สุดท้ายของวัตถุในเมทริกซ์หลังจากทำตามคำสั่งที่กำหนด เราจะถือว่าตำแหน่งเซลล์สุดท้ายมีอยู่ในเมทริกซ์ สมมติว่าสตริงคำสั่งเหมือนกับ "DDLRULL" ตำแหน่งเริ่มต้นคือ (3, 4) ตำแหน่งสุดท้ายคือ (1, 5)
วิธีการนั้นง่าย นับจำนวนการเคลื่อนไหวขึ้น ลง ซ้ายและขวา จากนั้นหาตำแหน่งสุดท้าย (x’, y’) โดยใช้สูตร -
(x’, y’) = (x + count_right – count_left,y + (count_down – count_up))
ตัวอย่าง
#include<iostream>
using namespace std;
void getFinalPoint(string command, int x, int y) {
int n = command.length();
int count_up, count_down, count_left, count_right;
int x_final, y_final;
count_up = count_down = count_left = count_right = 0;
for (int i = 0; i < n; i++) {
if (command[i] == 'U')
count_up++;
else if (command[i] == 'D')
count_down++;
else if (command[i] == 'L')
count_left++;
else if (command[i] == 'R')
count_right++;
}
x_final = x + (count_right - count_left);
y_final = y + (count_down - count_up);
cout << "Final Position: " << "(" << x_final << ", " << y_final << ")";
}
int main() {
string command = "DDLRULL";
int x = 3, y = 4;
getFinalPoint(command, x, y);
} ผลลัพธ์
Final Position: (1, 5)