【问题描述】
给定一个n×m矩阵相乘,求它的转置。其中1≤n≤20,1≤m≤20,矩阵中的每个元素都在整数类型(4字节)的表示范围内。
【输入格式】
第一行两个整数n和m;
第二行起,每行m个整数,共n行,表示n×m的矩阵。数据之间都用一个空格分隔。
【输出格式】
共m行,每行n个整数,数据间用一个空格分隔,表示转置后的矩阵。
样例输入
2 4 34 76 -54 7 -4 5 23 9
样例输出
34 -4 76 5 -54 23 7 9
思路图
提交测试情况
提交代码
import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt();//n行 int m = sc.nextInt();//m列 int [][] number = new int[n][m];//存放输入的矩阵 int [][] zhuanzhi = new int[m][n];//存放转置后的矩阵 for (int i = 0; i < n ; i++) { for (int j = 0; j < m; j++) { number[i][j] = sc.nextInt(); } } for(int x=0;x<n;x++){ for(int y=0;y<m;y++){ zhuanzhi[y][x] = number[x][y]; } } for(int x=0;x<m;x++){ for(int y=0;y<n;y++){ System.out.print(zhuanzhi[x][y]+" "); } System.out.println(); } } }
带注释的测试代码
package 蓝桥杯; import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // int n = sc.nextInt();//n行 // int m = sc.nextInt();//m列 int n = 2; int m = 4; // int [][] number = new int[n][m];//存放输入的矩阵 int [][] zhuanzhi = new int[m][n];//存放转置后的矩阵 int [][] number = {{34,76,-54,7},{-4,5,23,9}}; // for (int i = 0; i < n ; i++) { // for (int j = 0; j < m; j++) { // number[i][j] = sc.nextInt(); // } // } // int[][] arr = { {1,2,3}, // {4,5,6}, // {7,8,9}}; // for(int x=0;x<number.length;x++){ // for(int y=0;y<number[x].length;y++){ // System.out.print(number[x][y]+" "); // } // System.out.println(); // } for(int x=0;x<n;x++){ for(int y=0;y<m;y++){ zhuanzhi[y][x] = number[x][y]; // System.out.println(number[x][y]+" "); } // System.out.println("---"); } for(int x=0;x<m;x++){ for(int y=0;y<n;y++){ System.out.print(zhuanzhi[x][y]+" "); } System.out.println(); } } } /* 34 76 -54 7 -4 5 23 9 */

