Algorithms 练习1.1.13

xiaoxiao2021-02-28  63

要求编写将M行N列的二维数组的转置矩阵输出的程序,在此采用了String 数组,程序如下:

import edu.princeton.cs.algs4.StdOut; public class Test { public static void transposition(String [][] matrix){ int m = matrix.length; int n = matrix[0].length; int max = (m > n) ? m : n; //最大行列数 String [][] tempMatrix = new String[max][max]; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ tempMatrix[i][j] = matrix[i][j]; } } String temp = new String(); for(int i = 0; i < tempMatrix.length; i++){ for(int j = 0; j < i; j++){ temp = tempMatrix[i][j]; tempMatrix[i][j] = tempMatrix[j][i]; tempMatrix[j][i] = temp; } } StdOut.println("\nThe matrix of transposition:\n"); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ StdOut.print(tempMatrix[i][j] +" "); } StdOut.println(); } } public static void main(String[] args) { String [][] matrix = new String[4][6]; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ matrix[i][j] = "" + i + j; StdOut.print(matrix[i][j] + " "); } StdOut.println(); } transposition(matrix); } }

运行结果如图:

jimmysun的方法:

package com.jimmysun.algorithms.chapter1_1; public class Ex13 { public static void printTransposedMatrix(int[][] matrix) { for (int i = 0; i < matrix[0].length; i++) { for (int j = 0; j < matrix.length; j++) { System.out.printf("M", matrix[j][i]); } System.out.println(); } } public static void main(String[] args) { int[][] a = { { 100, 200, 300 }, { 400, 500, 600 } }; printTransposedMatrix(a); } }

因为只要求输出转置矩阵,并不要求使用,所以在满足要求的情况下,jimmy的程序明显好太多。

转载请注明原文地址: https://www.6miu.com/read-43009.html

最新回复(0)