Given an image represented by an NxN matrix, where each pixel in the imageis 4bytes, write a method to rotate the image by 90 degrees Can you do this in place?
描述:給定一個N*N的影像,每個位置的畫素是4byte,寫一個方法用來在原來的空間內旋轉影像90度。
思路:我們可以按層來旋轉。
void matrixRotation(int [][]a,int n)
{
for(int layer=0;layer<n;layer++)
{
int first=layer;
int last = n-layer-1;
for(int i=first;i<last;i++)
{
int offset=i-first;
int top =a[first][i];
a[first][i]=a[last-offset][first];//left->top
a[last-offset][first]=a[last][last-offset];//bottom->left
a[last][last-offset]=a[i][last];//right->bottom
a[i][last]=top;//top->right
}
}
}