我正在研究旋转NxN矩阵的这段代码;我已无数次追踪该程序,我有点理解实际旋转是如何发生的.它基本上首先旋转角落,然后沿角落顺时针旋转角落后的元素.我只是不理解几行,而且我的大脑中的代码仍然没有“驱动回家”,可以这么说.请帮忙.我将它旋转90度,给出一个4×4矩阵作为我的跟踪示例.
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
变
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
public static void rotate(int[][] matrix, int n){
for(int layer=0; layer < n/2; ++layer) {
int first=layer; //It moves from the outside in.
int last=n-1-layer; //
for(int i=first; i
int offset=i-first; //
//save the top left of the matrix
int top = matrix[first][i];
//shift left to top;
matrix[first][i]=matrix[last-offset][first];
/*I understand that it needs
last-offset so that it will go up the column in the matrix,
and first signifies it's in the first column*/
//shift bottom to left
matrix[last-offset][first]=matrix[last][last-offset];
/*I understand that it needs
last-offset so that the number decreases and it may go up the column (first
last-offset) and left (latter). */
//shift right to bottom
matrix[last][last-offset]=matrix[i][last];
/*I understand that it i so that in the next iteration, it moves down
the column*/
//rightmost top corner
matrix[i][last]=top;
}
}
}