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)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP