Last Updated: September 12, 2021
·
345
· Bruno Volpato

Transpose matrix in Java

public int[][] transpose(int[][] m) {
    int[][] ans = new int[m[0].length][m.length];
    for (int rows = 0; rows < m.length; rows++) {
        for (int cols = 0; cols < m[0].length; cols++) {
            ans[cols][rows] = m[rows][cols];
        }
    }

    return ans;
}