Title:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9]],rotate the input matrix in-place such that it becomes:[ [7,4,1], [8,5,2], [9,6,3]]
Example 2:
Given input matrix =[ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16]], rotate the input matrix in-place such that it becomes:[ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11]]
这道题是将一个矩阵旋转90度,需要的是不用额外的数组空间来完成,因此要找规律,规律如下:
[ [1,2,3], [4,5,6], [7,8,9]],变换为:
[ [7,4,1], [8,5,2], [9,6,3]]转换成数组形式,也就是:
[0,0] [0,1] [0,2]
[1,0] [1,1] [1,2]
[2,0] [2,1] [2,2]
旋转90度如下:
[2,0] [1,0] [0,0]
[2,1] [1,1] [0,1]
[2,2] [1,2] [0,2]
因此规律很明显,对于每一行,顺序颠倒即可,比如第一行,[0,0]变换后为[2,0],也就是将第一行最后一个数字[0,2]的行与列调换,然后与第一个[0,0]调换即可。比如第二行[1,0]与第二行最后一个[1,2],[1,2]首先调换行与列[2,1],然后与第二行第一个[1,0]调换,当然[1,0]也要行列调换为[0,1]。
solution:
void rotate(int** matrix, int matrixRowSize, int matrixColSize) { int i,j; int tmp[matrixRowSize][matrixColSize]; int used[matrixRowSize][matrixColSize]; memset(tmp,0,sizeof(tmp)); memset(used,0,sizeof(used)); for (i=0;i这个解法有一个缺陷,新建了两个二维数组。
那么如果不新建数组完成呢,要用到另一种思路:首先以从对角线为轴翻转,然后再以x轴中线上下翻转即可得到结果。
1 2 3 9 6 3 7 4 1
4 5 6 --> 8 5 2 --> 8 5 2
7 8 9 7 4 1 9 6 3
solution:
void rotate(int** matrix, int matrixRowSize, int matrixColSize) { int i,j; int tmp; for (i=0;i