Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created April 20, 2012 08:09
Show Gist options
  • Save zac-xin/2427052 to your computer and use it in GitHub Desktop.
Save zac-xin/2427052 to your computer and use it in GitHub Desktop.
1.6 Given an image represented by an NxN 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?
public class RotateMatrix {
public static void main(String args[]){
int[][] matrix = {
{1, 2, 3 ,4 ,5 ,6},
{12, 13, 14, 15, 16, 17},
{23, 24, 25, 26, 27, 28},
{34, 35, 36, 37, 38, 39},
{45, 46, 47, 48, 49, 50},
{66, 67, 68, 69, 70, 71}
};
printMatrix(matrix);
rotate(matrix, 6);
System.out.println("after rotate:");
printMatrix(matrix);
}
public static void printMatrix(int[][] data){
int i, j;
int row = data.length;
int column = data[0].length;
for(i = 0; i < row; i++){
for(j = 0; j < column; j++)
System.out.printf("%3d", data[i][j]);
System.out.println();
}
}
/* 分成n/2 layer进行rotate
* 每一层中 又有last-layer个step
*/
public static void rotate(int[][] data, int n){
int step;
int layer;
for(layer = 0; layer < n/2; layer++){
/* last是在这一层中最大的index值
* eg. n = 6; 那么layer = 0时, 也就是最开始, last = 5;
* 到了第二层 layer = 1; last 就是4了;
*/
int last = n - 1 - layer;
/* 在每一层Layer中 需要的step也是不同的 最外圈是0到n-2个step 数量是n-1
* 到了第二层 就是 0到 n-2-2 了
* 正好是last - layer (画个图会更明白)
*/
for(step = 0; step < last - layer ; step++){
int backup = data[step + layer][layer];
data[step + layer][layer] = data[last][step + layer];
data[last][step + layer] = data[last - step][last];
data[last-step][last] = data[layer][last - step];
data[layer][last-step] = backup;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment