图像由像素点表示。旋转 NxN 像素大小的图片九十度,每个像素点由数组中的一个元素表示。
Image is represented by pixels.Rotate an NxN image matrix by 90 degrees,where each pixel is given by each element in an array.
旋转可以针对每一层来实现,对于每一层从边上开始进行循环的交换,从第一层开始旋转(最外层的边)。从第一层的角落开始对边做四次交换的旋转,然后对边上顺时针的元素操作。当外层的元素旋转完,旋转内层的元素。
关于旋转后数组内元素是如何变换的,借助下图简单说明。点(1,1)变为(1,4)第一列变为第一行1+4 = 5 (1,2)变为(2,4) 1+4=5
The rotation can be performed in layers, where you perform a cyclic swap on the edges on
each layer In the first for loop, we rotate the first layer (outermost edges) We rotate the
edges by doing a four-way swap first on the corners, then on the element clockwise from the
edges, then on the element three steps away
Once the exterior elements are rotated, we then rotate the interior region's edges
void rotate(int [][]Matrix,int n)
{
for (int layer = 0 ;layer < n/2;layer++)
{
int first = layer;
int last = n-1-layer;
for (int i = first;i<last;i++)
{
int top = Matrix[first][i];//旋转元素
Matrix[first][i] = Matrix[n-1-i][first];
Matrix[n-1-i][first] = Matrix[n-1-first][n-1-i];
Matrix[n-1-first][n-1-i] = Matrix[i][n-1-first];
Matrix[i][n-1-first] = top;
}
}
}