图像旋转翻转变换 C++ 代码

题目描述:
给定 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值