題目描述
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.
解決思路
這題的難點(diǎn)在就地置換上悠反,采取先對(duì)角線交換元素再行順序倒置元素的思路來解決問題
如圖所示
沿對(duì)角線交換元素:
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;
//按照對(duì)角線對(duì)換元素
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;
}
}
}