You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Java:
1. 水平也就是上下转 然后对角线转 http://blog.youkuaiyun.com/fightforyourdream/article/details/14640155
// 矩阵顺时针转90度:先沿中线水平翻转,再沿着对角线翻转
// eg:
/*
1 2 3 7 8 9 7 4 1
4 5 6 => 4 5 6 => 8 5 2
7 8 9 1 2 3 9 6 3
*/
public void rotate(int[][] matrix) {
int len = matrix.length;
// 先沿中线水平翻转
for(int i=0; i<len/2; i++){
for(int j=0; j<len; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[len-1-i][j];
matrix[len-1-i][j] = tmp;
}
}
// 再沿着对角线翻转
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
2. 先对角线转 前后转就是垂直转 http://www.cnblogs.com/longhorn/p/3535341.html
public static void rotate1(int[][] matrix) {
if (matrix.length == 0) return;
transpose(matrix);
int col = matrix.length;
for(int i=0; i<col; i++) {
for (int j=0; j<col/2; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][col-1-j];
matrix[i][col-1-j] = tmp;
}
}
}
public static void transpose(int[][] matrix) {
for (int i=0; i<matrix.length; i++) {
for(int j=i; j<matrix[0].length; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}