二维数组逆时针旋转90c++
时间: 2023-09-04 13:16:16 浏览: 108
acq.rar_stc90c58rd+
可以通过先对二维数组进行转置,再将每一行反转来实现逆时针旋转90度。
以下是示例代码:
```c++
#include <iostream>
using namespace std;
void rotate(int arr[][3], int n) {
// 转置矩阵
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
}
// 每一行反转
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int tmp = arr[i][j];
arr[i][j] = arr[i][n - j - 1];
arr[i][n - j - 1] = tmp;
}
}
}
int main() {
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << "原始矩阵:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
rotate(arr, 3);
cout << "旋转后的矩阵:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
原始矩阵:
1 2 3
4 5 6
7 8 9
旋转后的矩阵:
3 6 9
2 5 8
1 4 7
```
阅读全文