Topic 1.6 Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
// 方法一:简单。考虑顺时针翻转,matrix[i][j]->matrix[j][n-1-i],但这需要额外开辟一个数组O(n)来存储,不是in place.
// 方法二:简单。左旋转:先转置(交换对角线),再交换行i和行n-1-I; (transpose, change rows). Time:O(n2)
右旋转:先转置,再交换列j和列n-1-j. (transpose, change columns)
//方法三:简单。这个跟方法一其实是一样的,原理都是matrix[i][j]->matrix[j][n-1-i],方法一从第一行开始转,方法三从最外面一层开始转,所以i,j的标记有变化。
右旋转:从最外面一层转到最里面一层。所以j始终是从i开始到n-1-i结束。
上边的存起来,左边的转到上边,上边的转到右边,右边的转到下边,下边的转到左边。
Time:O(n2), the best we can do since much touch all elements.
public class C1_1 {
public static void print(int[][] matrix) {
int n = matrix.length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
System.out.print(' ');
}
System.out.println();
}
}
public static void transpose(int[][] matrix) {
int n = matrix.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循环里面i,j的顺序
public static void changeRows(int[][] matrix){
int n=matrix.length;
for(int j=0;j<n;j++){
for(int i=0;i<n/2;i++){
int temp=matrix[i][j];
matrix[i][j]=matrix[n-1-i][j];
matrix[n-1-i][j]=temp;
}
}
}
public static void changeColumns(int[][] matrix) {
int n = matrix.length;
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-1-j];
matrix[i][n-1-j] = temp;
}
}
}
public static void rotate_clockwise1(int[][] matrix) {
transpose(matrix);
changeColumns(matrix);
}
public static void rotate_reverse_clockwise(int[][] matrix) {
transpose(matrix);
changeRows(matrix);
}
public static void rotate_clockwise2(int[][] matrix){
int n= matrix.length;
for(int i=0;i<n/2; i++){
for(int j=i;j<n-1-i;j++){//注意这里
int top=matrix[i][j];
//left->top
matrix[i][j]=matrix[n-1-j][i];
//bottom->left
matrix[n-1-j][i]=matrix[n-1-i][n-1-j];
//right->bottom
matrix[n-1-i][n-1-j]=matrix[j][n-1-i];
//top->right
matrix[j][n-1-i]=top;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
System.out.println("before");
print(matrix);
System.out.println("rotate clockwise");
rotate_clockwise2(matrix);
print(matrix);
}
}
// 结果
before
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
rotate clockwise
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4