Home > database >  Inplace transpose of a matrix in Java
Inplace transpose of a matrix in Java

Time:06-02

I'm trying a simple intuition to transpose a matrix in place.

I'm trying to swap elements of matrix[i][j] and matrix[j][i] but it is not working, I'm wondering what is happening behind the scene.

class Solution {
    public int[][] transpose(int[][] matrix) {
        
        
        for(int i = 0; i < matrix.length; i  ){
            for(int j = 0; j < matrix[0].length; j  ){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        
        return matrix;
    }
}

Output

For matrix -> [[1,2,3],[4,5,6],[7,8,9]]

It is giving output -> [[1,2,3],[4,5,6],[7,8,9]]

but the expected output should be -> [[1,4,7],[2,5,8],[3,6,9]]

CodePudding user response:

You are transposing each pair of elements twice, which puts them back how they were.

One solution would be to change for(int j = 0; in the inner loop to for(int j = i 1;. This would make sure that each pair of elements is only transposed once.

Also be aware that this general solution only works for square matrices.

CodePudding user response:

how about this way?

public int[][] transpose(int[][] matrix) {
    int[][] result = new int[matrix.length][matrix[0].length];
    for(int i = 0; i < matrix[0].length; i  ){
        for(int j = 0; j < matrix.length; j  ){
            result[j][i] = matrix[i][j];
            System.out.println(Arrays.deepToString(result));
        }
    }

    return result;
}
  • Related