Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Solution1
- 这道题无非是一些边界条件的把握。
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int i=0;i<n/2;i++){
for(int j=i;j<n-i-1;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = temp;
}
}
}
}
Solution2
- 有更加trick的解法,如下
public class Solution {
public void rotate(int[][] matrix) {
for(int i=0,j=matrix.length-1;i<j;i++,j--){
int[] temp = matrix[i];
matrix[i] = matrix[j];
matrix[j] = temp;
}
for(int i=0;i<matrix.length;i++){
for(int j=0;j<i;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
}
更详细的解释在顺时针和逆时针都可以用类似方法