这是一个来自《Cracking the Coding Interview》的问题。解决方案表示程序先旋转外部边缘,然后旋转内部边缘。然而,我很难理解两个for循环的逻辑。有人能解释一下代码的逻辑吗(例如为什么要执行“layer < n/2”以及“左侧->上侧”和“底部->左侧”等四个步骤)?另外,如果在编程面试中想出这个方法,思考过程会是怎样的?
给定一个由N×N矩阵表示的图像,其中图像中的每个像素占用4个字节,请编写一种方法将图像旋转90度。你能原地完成吗?
public static void rotate(int[][] matrix, int n) {
for (int layer = 0; layer < n / 2; ++layer) {
int first = layer;
int last = n - 1 - layer;
for(int i = first; i < last; ++i) {
int offset = i - first;
int top = matrix[first][i]; // save top
// 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; // right <- saved top
}
}
}