题目描述
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.
解决思路
这题的难点在就地置换上,采取先对角线交换元素再行顺序倒置元素的思路来解决问题
如图所示
沿对角线交换元素:
1 2 3 => 1 4 7
4 5 6 => 2 5 8
7 8 9 => 3 6 9
行顺序倒置元素:
1 4 7 => 7 4 1
2 5 8 => 8 5 2
3 6 9 => 9 6 3
代码
public void rotate(int[][] matrix) {
int n = matrix[0].length;
//按照对角线对换元素
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//行顺序倒置
for(int i=0;i<n;i++){
for(int j=0;j<n/2;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n-j-1];
matrix[i][n-j-1] = temp;
}
}
}