Java小记-矩阵转置

对于给定的一个二维矩阵,请转置后进行输出。

输入描述

对于一个n*m的矩阵,输入有n行,每行是m个以空格分隔的数字。

输出描述

n*m矩阵的转置矩阵。输出m行,每行是n个空格分隔的数据。

java 复制代码
import java.io.*;
import java.util.*;

public class ZhuanZhi {

	public static void main(String args[]) {

		String input = "1 2 3\r\n" + "4 5 6";
		Scanner cin = new Scanner(input);
		ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
		while (cin.hasNextLine()) {
			ArrayList<Integer> row = new ArrayList<Integer>();
			String line = cin.nextLine();
			if (line.length() > 0) {
				String[] arrLine = line.split(" ");
				for (int i = 0; i < arrLine.length; i++) {
					row.add(Integer.parseInt(arrLine[i]));
				}
				arr.add(row);
			}
		}

		new Solution().myFunc(arr);
	}
}

class Solution {
	public void myFunc(ArrayList<ArrayList<Integer>> arr) {
		if (!(arr == null || arr.isEmpty() || arr.get(0).isEmpty())) {
			ArrayList<Integer> row = new ArrayList<Integer>();
			int r = arr.size();
			int l = arr.get(0).size();
			int[][] nn = new int[l][r];
			
			for (int i = 0; i < r; i++) {
				row = arr.get(i);
				for (int j = 0; j < row.size(); j++) {
					nn[j][i] = (row.get(j));
				}
			}
			
			for (int i = 0; i < l; i++) {
				for (int j = 0; j < r; j++) {
					System.out.print(nn[i][j] + " ");
				}
				System.out.println();
			}
		}
	}
}
相关推荐
Gerardisite6 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5956 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan6 小时前
【C++】多态
开发语言·c++
gfdhy7 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程7 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
Eiceblue7 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY7 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍7 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel
leon_zeng07 小时前
Qt Modern OpenGL 入门:从零开始绘制彩色图形
开发语言·qt·opengl
会飞的胖达喵7 小时前
Qt CMake 项目构建配置详解
开发语言·qt