算法(第4版) 1.1.13

编写一段代码,打印出一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值