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