题目描述:
给定 m行 n列的图像各像素点灰度值,对其依次进行一系列操作后,求最终图像。
其中,可能的操作及对应字符有如下四种:
A:顺时针旋转 90度;
B:逆时针旋转 90度;
C:左右翻转;
D:上下翻转。
输入:
第一行包含两个正整数m和n,表示图像的行数和列数,中间用单个空格隔开。1<≤m≤100,1≤n≤100。
接下来m行,每行n个整数,表示图像中每个像素点的灰度值,相邻两个数之间用单个空格隔开。灰度值范围在0到255之间。
接下来一行,包含由A、B、C、D组成的字符串s,表示需要按顺序执行的操作序列。s的长度在1到100之间。
输出:
m′行,每行包含n′个整数,为最终图像各像素点的灰度值。其中m′为最终图像的行数,n′为最终图像的列数。相邻两个整数之间用单个空格隔开。
【输入样例】
2 3
10 0 10
100 100 10
AC
【输出样例】
10 100
0 100
10 10
请使用C++ 代码实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to rotate the matrix clockwise by 90 degrees
void rotateClockwise(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> result(n, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
result[j][m - 1 - i] = matrix[i][j];
}
}
matrix = result;
}
// Function to rotate the matrix counterclockwise by 90 degrees
void rotateCounterClockwise(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> result(n, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
result[n - 1 - j][i] = matrix[i][j];
}
}
matrix = result;
}
// Function to flip the matrix left-to-right
void flipHorizontal(vector<vector<int>>& matrix) {
for (auto& row : matrix) {
reverse(row.begin(), row.end());
}
}
// Function to flip the matrix top-to-bottom
void flipVertical(vector<vector<int>>& matrix) {
reverse(matrix.begin(), matrix.end());
}
int main() {
int m, n;
cin >> m >> n;
vector<vector<int>> matrix(m, vector<int>(n));
// Input the matrix
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> matrix[i][j];
}
}
string operations;
cin >> operations;
// Apply each operation in sequence
for (char op : operations) {
if (op == 'A') {
rotateClockwise(matrix);
} else if (op == 'B') {
rotateCounterClockwise(matrix);
} else if (op == 'C') {
flipHorizontal(matrix);
} else if (op == 'D') {
flipVertical(matrix);
}
}
// Output the resulting matrix
m = matrix.size();
n = matrix[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cout << matrix[i][j];
if (j != n - 1) cout << " ";
}
cout << endl;
}
return 0;
}