C ++中矩阵中最终单元的位置
假设我们有一组作为字符串的命令,该字符串将在四个方向上具有四个不同的字母。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)
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练