48.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]
]
1.矩阵旋转90度;
2.不允许使用新矩阵,只能在原矩阵上进行操作;
1.矩阵元素交换原理
2.由于90度旋转,每个数字对应旋转四个位置,例如例1中的 1,7,9,3四个角落数字旋转之后的对应关系为7,9,3,1;
3.设置对应关系,如下:
其中i为行数,j为列数
Height 为高度,Width为宽度
起始位置:matrix[i][j]
逆时针90度位置:
matrix[Height - j - 1][i]
逆时针180度位置:
matrix[Width- i- 1][Height - j- 1]
逆时针270度位置:
matrix[j][Width- i - 1]
4.此题规律: m[i][j] = m[n-1-j][i]
@Test
public void TestRotateImage(){
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
rotate(matrix);
int[][] test = matrix;
}
//[1,2,3]
//[4,5,6]
//[7,8,9]
public void rotate(int[][] matrix) {
int lenWidth = matrix.length;//3
if(lenWidth == 0){
return;
}
int lenHeight = matrix[0].length;//3
int k = lenWidth;//3
int temp;
//i = 0 ; j = 0;
for(int i = 0;i < lenHeight / 2;i++){
for(int j = i;j < k - 1;j++){
temp = matrix[i][j];//1
matrix[i][j] = matrix[lenHeight - j - 1][i];//7
matrix[lenHeight - j - 1][i] = matrix[lenHeight - i - 1][lenWidth - j -1];//9
matrix[lenHeight - i -1][lenWidth - j -1] = matrix[j][lenWidth - i -1];//3
matrix[j][lenWidth - i - 1] = temp;
}
k--;
}
return;
}
总结:
1.此题需要总结出位置元素置换规律;
2.不能新生成矩阵,否则此题就没意义啦;
3.欢迎大家,留言评论,大家一起进步,噢力给!