How to swap rows and columns of a 2d array?

后端 未结 2 638
死守一世寂寞
死守一世寂寞 2021-01-23 03:54

I\'m trying to write a method for \'transpose\' a two-dimensional array of integers, in which the rows and columns of the original matrix are exchanged.

However, I have n

2条回答
  •  青春惊慌失措
    2021-01-23 04:38

    You could iterate over the rows and columns and assign each element [i,j] to the transposed [j,i]:

    /**
     * Transposses a matrix.
     * Assumption: mat is a non-empty matrix. i.e.:
     * 1. mat != null
     * 2. mat.length > 0
     * 3. For every i, mat[i].length are equal and mat[i].length > 0
     */
    public static int[][] transpose(int[][] mat) {
        int[][] result = new int[mat[0].length][mat.length];
        for (int i = 0; i < mat.length; ++i) {
            for (int j = 0; j < mat[0].length; ++j) {
                result[j][i] = mat[i][j];
            }
        }
        return result;
    }
    

提交回复
热议问题