给你一幅由 N × N
矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?思路:顺时针旋转90度,可以在纸上画一画,看一下坐标变换;很容易发现规律,横纵坐标交换,并且纵坐标对应序列,变换为反序,size-1-y
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int matrix_size = matrix.size();
vector<vector<int>> result(matrix_size, vector<int>(matrix_size));
for (int i = 0; i < matrix_size; i++){
for (int j = 0; j < matrix_size; j++){
result[j][matrix_size-1-i] = matrix[i][j];
}
}
matrix = result;
}
};
int main(){
Solution s;
vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
s.rotate(matrix);
for (int i = 0; i < matrix.size(); i++){
for (int j = 0; j < matrix.size(); j++){
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}