您好,欢迎来到宝玛科技网。
搜索
您的当前位置:首页二维数组旋转90度C语言,algorithm – 将二维数组旋转90度

二维数组旋转90度C语言,algorithm – 将二维数组旋转90度

来源:宝玛科技网

我正在研究旋转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;

}

}

}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baomayou.com 版权所有 赣ICP备2024042794号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务