编写一段代码,打印出一个M行N列的二维数组的转置(交换行和列)
package temporary;
import edu.princeton.cs.algs4.*;
public class Practice {
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.print("请输入数组行:");
int M=StdIn.readInt();
System.out.print("请输入数组列:");
int N=StdIn.readInt();
int[][] a=new int[M][N];
for(int i=0;i<M;i++) {
for(int j=0;j<N;j++) {
//给数组元素赋值
a[i][j]=(int) (100*Math.random());
System.out.print(a[i][j]+" ");
}
System.out.println();
}
Reform(a);
}
//对于数组进行转置
public static void Reform(int[][] a){
int M=a.length;//获取a的行数
int N=a[0].length;//获取a的列数
int[][] b=new int[N][M];
int i;
int j;
for(i=0;i<M;i++) {
for(j=0;j<N;j++) {
b[j][i]=a[i][j];
}
}
System.out.println();
for(i=0;i<N;i++) {
for(j=0;j<M;j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}
程序运行结果示例:
请输入数组行:5
请输入数组列:3
55 54 97
1 31 4
40 57 88
67 41 90
9 25 41
55 1 40 67 9
54 31 57 41 25
97 4 88 90 41