给定一幅由N × N矩阵表示的图像,其中每个像素的大小为4字节,编写一种方法,将图像旋转90度。
不占用额外内存空间能否做到?
![7898366-844ced4cb1fd1a22.png](https://i-blog.csdnimg.cn/blog_migrate/e42aaacef742ea9a4f03e72ff5050221.png)
image.png
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i = 0;i < n / 2;i++)
{
int first = i;
int last = n - 1 - i;
for(int j = first;j < last;j++)
{
int offset = j - first;
int top = matrix[first][j];
matrix[first][j] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];
matrix[last][last-offset] = matrix[j][last];
matrix[j][last] = top;
}
}
}