假设我们有一组作为字符串的命令,该字符串将在四个方向上具有四个不同的字母。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)