实例043 Java将二维数组的行列互换

发布时间 2023-05-04 17:56:45作者: 两拳ko小yu

可以通过以下代码将二维数组的行列互换:

public static void transpose(int[][] matrix) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    int[][] result = new int[cols][rows];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[j][i] = matrix[i][j];
        }
    }
    
   //输出转置后的矩阵
   System.out.println("原始矩阵:");
   printMatrix(matrix);
   
   System.out.println("转置后的矩阵:");
   printMatrix(result); 
}

//打印二维数组中每个元素,用于调试和验证结果是否正确。
private static void printMatrix(int[][] arr){
     for(int[] row : arr){
         StringBuilder sb=new StringBuilder();
         for(int col:row)
             sb.append(col).append("\t");  
          System.out.println(sb.toString());
      }     
}

  其中,参数matrix表示要进行转置的二维数组。首先获取原数组的行数和列数,然后创建一个新的二维数组result,行数为原数组的列数,列数为原 数组 的 行 数 。 接 着 ,通 过 双重循环 遍 历 原 数 组,并 将 原 数 组 中 每个 元 素 的 行 列 互 换 后 存入 新 数 组 中 。 最 后 ,遍历新数据并输出 转 移 结 果 。