我正在学习旋转NxN矩阵的代码;我已经反复追踪了程序,也有点理解实际旋转发生的方式。它基本上先按顺时针方向旋转角落,然后再旋转角落后的元素。但是还有几行代码我不理解,这段代码还没有完全被我掌握。请帮忙。 我的示例是一个4x4的矩阵,需要将其旋转90度。
[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; //<--This I do not understand
for(int i=first; i<last;++i){
int offset=i-first; //<--A bit confusing for me
//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;
}
}
}