题目描述
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
解题思路
如下图所示:
方阵顺时针旋转90度不难,复杂的是如何原地置换。上图中给出了一个方案。我们可以将问题划分为更简单的问题,即将方阵的每一层顺时针旋转(因为去掉最外层里头仍然是一个方阵)。
那么如何旋转一层呢?
我们可以将一个n*n的方阵最外层按边分为四组,每组元素为n-1个,每次顺时针将每组对应的元素进行置换(如上图所示),即可解决.
例如:旋转前,由左上角顺时针一次为a[0][0]->a[0][n-1] ->a[n-1][n-1]->a[n-1][0];旋转后为a[n-1][0]->a[0][0]->a[0][n-1] ->a[n-1][n-1];
代码
public static void rotate(int[][] matrix) {
int n = matrix.length;
int m = 0;
for (int i = n - 1; i > 0; i--) {
m = n - 1 - i;
for(int j = m;j < i;j++){
//方阵左上角的matrix[j][i]记录每次旋转的值
int temp = matrix[j][i];
matrix[j][i] = matrix[m][j];
matrix[m][j] = temp;
temp = matrix[i][i - j + m];
matrix[i][i - j + m] = matrix[m][j];
matrix[m][j] = temp;
temp = matrix[i - j + m][m];
matrix[i - j + m][m] = matrix[m][j];
matrix[m][j] = temp;
}
}
}