问题
有一个MxN的矩阵,设计函数将其顺时针旋转90度。
打印示例
Original matrix:
1 2 3
4 5 6
7 8 9
Rotated matrix (90 degrees clockwise):
7 4 1
8 5 2
9 6 3
代码
#include <iostream>
#include <vector>
using namespace std;
void rotateMatrix90Clockwise(const vector<vector<int>>& matrix, vector<vector<int>>& result) {
int M = matrix.size();
int N = matrix[0].size();
// Resize the result matrix to be N x M
result.resize(N, vector<int>(M, 0));
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
// Place element matrix[i][j] into the correct position in result
result[j][M - 1 - i] = matrix[i][j];
}
}
}
void printMatrix(const vector<vector<int>>& matrix) {
for (const auto& row : matrix) {
for (int val : row) {
cout << val << ' ';
}
cout << endl;
}
}
int main() {
// Example usage
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
vector<vector<int>> rotatedMatrix;
rotateMatrix90Clockwise(matrix, rotatedMatrix);
cout << "Original matrix:" << endl;
printMatrix(matrix);
cout << "Rotated matrix (90 degrees clockwise):" << endl;
printMatrix(rotatedMatrix);
return 0;
}
标签:const,matrix,int,矩阵,c++,旋转,vector,result
From: https://www.cnblogs.com/azureology/p/18374735