题目地址: Rotate Image
描述:
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度后的组合。要求:原地旋转(不能使用其他的二维数据空间);
基本思想:从左上角的点开始循环,i=1;首先1,1,14,14四个点,顺时针交换,i=2;是4,2,14,2,顺时针再交换;i
=3; 7,3,14,3,顺时针交换;i=4;7,12,10,2顺时针交换;接着是进入迭代,迭代就是第二次正方形,如图所示,然后进行和上面一样的for循环操作。
public class RotateImage {
public static void main(String[] args) {
int[][] arr = { { {1,4,7,7,1},{2,5,8,8,2},{3,6,9,9,3},{12,9,11,11,12},{14,10,14,14,14}}};
rotate(arr);
System.out.println(Arrays.toString(arr));
}
private static void rotate(int[][] matrix){
int length = matrix.length;
iteration(matrix,length,0);
}
//先是最外层,然后迭代每一层。
private static void iteration(int[][] matrix, int len, int index) {
if (len - index < 2) {
return;
}
int j = len -1;
int temp, tem;
//循环交换每一层的数字
for (int i = 0; i+index < j; i++) {
temp = matrix[i+index][j];
matrix[i+index][j] = matrix[index][i+index];
tem = matrix[j][len - i-1];
matrix[j][len - i-1] = temp;
temp = matrix[j-i][index];
matrix[j-i][index] = tem;
matrix[index][i+index] = temp;
}
iteration(matrix,len-1,++index);
}
}