小编Nat*_*man的帖子

将二维阵列旋转90度

我正在研究旋转NxN矩阵的这段代码; 我已无数次追踪该程序,我有点理解实际旋转是如何发生的.它基本上首先旋转角落,然后沿角落顺时针旋转角落后的元素.我只是不理解几行,而且我的大脑中的代码仍然没有"驱动回家",可以这么说.请帮忙.我将它旋转90度,给出一个4x4矩阵作为我的跟踪示例.

[1][2][3][4] 
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Run Code Online (Sandbox Code Playgroud)

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
Run Code Online (Sandbox Code Playgroud)
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 …
Run Code Online (Sandbox Code Playgroud)

algorithm rotation matrix multidimensional-array

6
推荐指数
2
解决办法
8975
查看次数