Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
//注意二维数组的声明方法
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
void swap(int &x,int &y){
int tmp;
tmp=x;
x=y;
y=tmp;
}
void printArray(int a[][4],int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}//逆时针旋转90度
void trans(int a[][4],int n){
//先按对角线翻转
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
swap(a[i][j],a[j][i]);
//然后上下翻转
for(int i=0;i<n/2;i++)
for(int j=0;j<n;j++)
swap(a[i][j],a[n-1-i][j]);
}
int main(){
int a[][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
printArray(a,4);
trans(a,4);
printArray(a,4);
system("pause");
return 0;
}