Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาตำแหน่งเซลล์สุดท้ายในเมทริกซ์จากคำสั่งเคลื่อนที่ C++

ปัญหา

ให้สตริงคำสั่งที่ประกอบด้วย U (ขึ้น), D (ลง), L (ซ้าย), R (ขวา) และตำแหน่งเริ่มต้น (x, y) หาตำแหน่งสุดท้ายหลังทำตามคำสั่งทั้งหมด

ตัวอย่าง: คำสั่ง "DDLRULL", เริ่มที่ (3, 4) → ตำแหน่งสุดท้าย (1, 5)

วิธีแก้ปัญหา

นับจำนวนการเคลื่อนที่แต่ละทิศทาง แล้วคำนวณ:

x' = x + count_right - count_left
y' = y + count_down - count_up

ตัวอย่างโค้ด C++

#include <iostream>
#include <string>
using namespace std;

void getFinalPoint(string command, int x, int y) {
    int n = command.length();
    int count_up = 0, count_down = 0, count_left = 0, 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++;
    }
    
    int x_final = x + (count_right - count_left);
    int 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);
    return 0;
}

ผลลัพธ์

Final Position: (1, 5)