矩阵顺时针旋转90度

#include 
#include 
using namespace std;
void printMatrix(const std::vector<std::vector<int>>& matrix);
void rotateMatrix(std::vector<std::vector<int>>& matrix) {
    int n = matrix.size();

    // 转置矩阵
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            std::swap(matrix[i][j], matrix[j][i]);
        }
    }
    cout << "转置:" << endl;
    printMatrix(matrix);
    // 行翻转
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n / 2; j++) {
            std::swap(matrix[i][j], matrix[i][n - 1 - j]);
        }
    }
}

void printMatrix(const std::vector<std::vector<int>>& matrix) {
    int n = matrix.size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector<std::vector<int>> matrix{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

    std::cout << "旋转前的矩阵:" << std::endl;
    printMatrix(matrix);

    rotateMatrix(matrix);

    std::cout << "旋转后的矩阵:" << std::endl;
    printMatrix(matrix);

    system("pause");
    return 0;
}

你可能感兴趣的:(嵌入式秋招,矩阵,c++,算法)