二维数组旋转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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值