欢迎访问宙启技术站
智能推送

通过Java函数实现二维矩阵转置的方法

发布时间:2023-08-12 07:59:00

在Java中,可以通过编写一个函数来实现二维矩阵的转置。矩阵的转置是将原矩阵的行与列互换得到的新矩阵。下面是一个实现二维矩阵转置的Java函数的示例代码:

public class MatrixTranspose {
    public static int[][] 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];
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        int[][] transposedMatrix = transpose(matrix);

        System.out.println("原矩阵:");
        printMatrix(matrix);

        System.out.println("转置矩阵:");
        printMatrix(transposedMatrix);
    }

    public static void printMatrix(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

上述代码中,我们定义了一个transpose函数,该函数接受一个二维矩阵作为参数,并返回转置后的矩阵。该函数首先根据原矩阵的行数和列数创建一个新矩阵result,其中转置后的矩阵的行数等于原矩阵的列数,列数等于原矩阵的行数。然后,通过两个嵌套的循环遍历原矩阵的每个元素,并将其放入新矩阵的对应位置。

main函数中,我们创建了一个测试用的二维矩阵matrix,调用transpose函数进行转置操作,并将结果打印出来。为了方便,我们还定义了一个printMatrix函数,用于打印矩阵。

运行上述代码,将得到以下输出:

原矩阵:
1 2 3 
4 5 6 
7 8 9 
转置矩阵:
1 4 7 
2 5 8 
3 6 9 

以上就是通过Java函数实现二维矩阵转置的方法。这个函数可以适用于不同大小的二维矩阵,并且时间复杂度为O(rows * cols),其中rows为矩阵的行数,cols为矩阵的列数。