c++矩阵旋转问题
问题#
有一个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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架