矩阵顺时针旋转90度c++
时间: 2023-12-02 09:40:09 浏览: 121
阿里巴巴 云计算 C C++ 面试 试题
3星 · 编辑精心推荐
使用以下代码实现矩阵顺时针旋转90度:
```c++
#include <iostream>
using namespace std;
const int N = 4;
class Array {
private:
int a[N][N];
public:
Array(int b[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
a[i][j] = b[i][j];
}
}
}
void rotate() {
for (int i = 0; i < N / 2; i++) {
for (int j = i; j < N - i - 1; j++) {
int temp = a[i][j];
a[i][j] = a[N - j - 1][i];
a[N - j - 1][i] = a[N - i - 1][N - j - 1];
a[N - i - 1][N - j - 1] = a[j][N - i - 1];
a[j][N - i - 1] = temp;
}
}
}
void print() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
int b[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
Array arr(b);
arr.rotate();
arr.print();
return 0;
}
```
阅读全文