问题
编写一段代码,打印出一个M行N列的二维数组的转置(交换行和列)
代码
package com.klc.algs4practices;
import edu.princeton.cs.algs4.StdRandom;
public class Main {
public static void main(String[] args) {
int M = StdRandom.uniform(1, 11); // 返回 1-10之间的随机整数
int N = StdRandom.uniform(1, 11);
int[][] a = new int[M][N];
//随机初始化数组
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
a[i][j] = StdRandom.uniform(10);
}
}
for(int i = 0; i < a.length; i++){
for(int value:a[i]){
System.out.print(value+" ");
}
System.out.println();
}
//转置上述数组
int[][] trans = transpose(a);
for(int i = 0; i < trans.length; i++){
for(int value:trans[i]){
System.out.print(value+" ");
}
System.out.println();
}
}
public static int[][] transpose(int[][] a){
int M = a.length;
int N = a[0].length;
int[][] trans = new int[N][M];
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
trans[j][i] = a[i][j];
}
}
return trans;
}
}
输入结果如下: 3 1 7 6 6 6
7 7 8 5 4 1
3 7
1 7
7 8
6 5
6 4
6 1