समस्या विवरण
एक कमांड स्ट्रिंग दी गई है जिसमें U (ऊपर), D (नीचे), L (बाएं), R (दाएं) दिशाएं हैं। प्रारंभिक स्थिति (x, y) दी गई है। सभी कमांड का पालन करने के बाद अंतिम स्थिति ढूंढें।
उदाहरण: कमांड "DDLRULL", प्रारंभिक स्थिति (3, 4)। अंतिम स्थिति (1, 5)।
हल दृष्टिकोण
प्रत्येक दिशा की गिनती करें और अंतिम स्थिति की गणना करें:
(x', y') = (x + count_right - count_left, y + count_down - count_up)
उदाहरण कोड
#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)