1068. 图像旋转翻转变换
题目描述
给定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
数据范围限制
1 <= m <= 100, 1 <= n <= 100。
C++代码
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
const int max_rows = 100; // maximum rows
const int max_cols = 100; // maximum columns
class ImageMatrix
{
public:
int m_elments[max_rows+1][max_cols+1]; // row, col starts from 1
ImageMatrix(int rows, int cols) : m_rows(rows), m_cols(cols) {};
ImageMatrix Rotate90DegreesClockwise();
ImageMatrix Rotate90DegreesCounterclockwise();
ImageMatrix FlipLeftAndRight();
ImageMatrix FlipUpAndDown();
void printMatrixElements();
private:
int m_rows; // number of rows
int m_cols; // number of columns
};
ImageMatrix ImageMatrix::Rotate90DegreesClockwise()
{
ImageMatrix newMatrix(m_cols, m_rows);
for(int row=1; row<=m_rows; row++)
{
for(int col=1; col<=m_cols; col++)
{
newMatrix.m_elments[col][m_rows+1-row] = m_elments[row][col];
}
}
return newMatrix;
}
ImageMatrix ImageMatrix::Rotate90DegreesCounterclockwise()
{
ImageMatrix newMatrix(m_cols,m_rows);
for(int row=1; row<=m_rows; row++)
{
for(int col=1; col<=m_cols; col++)
{
newMatrix.m_elments[m_cols+1-col][row] = m_elments[row][col];
}
}
return newMatrix;
}
ImageMatrix ImageMatrix::FlipLeftAndRight()
{
ImageMatrix newMatrix(m_rows,m_cols);
for(int col=1; col<=m_cols; col++)
{
for(int row=1; row<=m_rows; row++)
{
newMatrix.m_elments[row][(m_cols+1)-col] = m_elments[row][col];
}
}
return newMatrix;
}
ImageMatrix ImageMatrix::FlipUpAndDown()
{
ImageMatrix newMatrix(m_rows, m_cols);
for(int row=1; row<=m_rows; row++)
{
for(int col=1; col<=m_cols; col++)
{
newMatrix.m_elments[(m_rows+1)-row][col] = m_elments[row][col];
}
}
return newMatrix;
}
void ImageMatrix::printMatrixElements()
{
for(int row=1; row<=m_rows; row++)
{
for(int col=1; col<=m_cols; col++)
{
cout << m_elments[row][col] << " ";
}
cout << endl;
}
}
int main()
{
int m, n;
cin >> m >> n;
assert(m>=1 && m<=max_rows);
assert(n>=1 && n<=max_cols);
ImageMatrix myMatrix(m, n);
for(int row=1; row<=m; row++)
{
for(int col=1; col<=n; col++)
{
cin >> myMatrix.m_elments[row][col];
}
}
string OpSeq;
cin >> OpSeq;
for(unsigned int i=0; i<OpSeq.size(); i++)
{
switch((char)OpSeq[i])
{
case 'A':
myMatrix = myMatrix.Rotate90DegreesClockwise();
break;
case 'B':
myMatrix = myMatrix.Rotate90DegreesCounterclockwise();
break;
case 'C':
myMatrix = myMatrix.FlipLeftAndRight();
break;
case 'D':
myMatrix = myMatrix.FlipUpAndDown();
break;
default:
break;
}
}
myMatrix.printMatrixElements();
return 0;
}