原文:
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?
译文:
一张图像表示成NxN的矩阵,图像中每个像素是4个字节,写一个函数把图像旋转90度。 你能原地进行操作吗?(即不开辟额外的存储空间)
N*N矩形,旋转90度,直观来看就是最外圈进行旋转,一层一层往里再进行旋转。
public static int[][] rotate(int[][] matrix, int n) {
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - first - 1;
for (int i = first; i < last; i++) {
int offset = i - first;
//Save top
int top = matrix[first][i];
// left->top
matrix[first][i] = matrix[last - offset][first];
//bottom->left
matrix[last - offset][first] = matrix[last][last - offset];
//right->bottom
matrix[last][last - offset] = matrix[i][last];
//top->right
matrix[i][last] = top;
}
}
return matrix;
}
junit testcase
@Test
public void testRotate() {
System.out.println("rotate");
int[][] test = {{1, 2}, {3, 4}};
int[][] expected = {{3, 1}, {4, 2}};
assertArrayEquals(expected, q1_6.rotate(test, 2));
int[][] test1 = {{1}};
int[][] expected1 = {{1}};
assertArrayEquals(expected1, q1_6.rotate(test1, 1));
int[][] test2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int[][] expected2 = {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}};
assertArrayEquals(expected2, q1_6.rotate(test2, 4));
int[][] test3 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] expected3 = {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}};
assertArrayEquals(expected3, q1_6.rotate(test3, 3));
}