您的位置:首页 > 其它

方阵顺时针旋转

2018-02-17 11:21 253 查看
对一个方阵转置,就是把原来的行号变列号,原来的列号变行号
例如,如下的方阵:
1  2 3  4
5  6 7  8
9 10 11 12
13 14 15 16
转置后变为:
1  5  9 13
2  6 10 14
3  7 11 15
4  8 12 16
但,如果是对该方阵顺时针旋转(不是转置),却是如下结果:
13  9 5  1
14 10  6  2
15 11  7  3
16 12  8  4
下面的代码实现的功能就是要把一个方阵顺时针旋转。

package com.company;

/**
* Created by Mr.Smart on 2018-01-23.
*/
public class Question20 {
public static void main(String[] args){
int[][] n = {
{1 ,2 ,3 ,4 },
{5 ,6 ,7 ,8 },
{9 ,10,11,12},
{13,14,15,16}
};
int[][] m = new int[n.length][n.length];
print(n);
ratotion(n,m,0,n.length-1);
print(m);

}

private static void ratotion(int[][] n, int[][] m, int i, int j) {
int t = j;
if (i>n.length-1) return;
for (int k=0;k<n.length;k++){
m[i][k] = n[j--][i];
}
ratotion(n,m,++i,t);
}

private static void print(int[][] n) {
for (int i=0;i<n.length;i++){
for (int j=0;j<n[i].length;j++){
System.out.print(n[i][j]+" ");
}
System.out.println();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: