在这个问题上,我们给了一个机器人,它可以在所有四个方向上移动,但只能移动一个方向。方向为上('U'),下('D'),左('L'),右('R')。然后,我们将得到一个包含数字方向首字母的字符串。给定机器人的初始位置为(0,0),我们的任务是打印机器人的最终位置。
让我们以一个例子来了解问题
输入-输入:'LDRRUL'
输出-(0,0)
说明-
L (left) : (0,0) -> (-1,0) D (down) : (-1,0) -> (-1, -1) R (right) : (-1, -1) -> (0, -1) R (right) : (0, -1) -> (1, -1) U(up) : (1, -1) -> (1, 0) L(left) : (1, 0) -> (0, 0)
为了解决这个问题,我们将计算在x轴和y轴方向上的移动总数。对于x坐标,请增加“向右移动”的计数,并减少向左移动的计数。对于y坐标,请增加向上移动的计数,并增加向左移动的计数。
显示我们解决方案实施情况的程序
#include <iostream>
#include <string.h>
using namespace std;
void robotMoved(string move) {
int xAxis, yAxis;
int l=move.size();
for (int i = 0; i < l; i++) {
if (move[i]=='U')
yAxis++;
else if (move[i]=='D')
yAxis--;
else if (move[i]=='L')
xAxis--;
else if (move[i]=='R')
xAxis++;
}
cout<<"Final Position of the robot is : ("<<xAxis<<", "<<yAxis<<")"<<endl;
}
int main() {
string move="URLLDDRRUDUDDRU";
robotMoved(move);
return 0;
}输出结果
Final Position of the robot is : (32744, -274873553)