给定一幅由N*N矩阵表示的图像,其中每个像素的大小为4字节,编写一个方法,将图像旋转90度。不占用额外内存空间能否做到?
package test;
public class RotateMatrix {
public static void rotateMatrix(int[][] matrix){
if(matrix==null || matrix.length==0 || matrix[0]==null || matrix[0].length==0)
return;
if(matrix.length != matrix[0].length)
return;
int n = matrix.length;
for(int layer=0; layer < n/2; layer++){
int first = layer;
int last = n-layer-1;
for(int i=first; i<last; i++){
int offset = i-first;
int temp = matrix[i][first];
matrix[i][first] = matrix[last][i];
matrix[last][i] = matrix[last-offset][last];
matrix[last-offset][last] = matrix[first][last-offset];
matrix[first][last-offset] = temp;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] case1 = null;
int[][] case2 = { {1,2,3}, {4,5,6}, {7,8,9} };
int[][] testCase = case2;
rotateMatrix(testCase);
for(int i=0; i<testCase.length; i++){
for(int j=0; j<testCase[0].length; j++){
System.out.print(testCase[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}