# Transpose of Matrix Inplace

Transpose of Matrix In-place

You are given a M * N matrix, find Transpose of Matrix in-place. Transpose of matrix is obtained by interchanging rows and columns of a matrix that is by changing rows to columns and columns to rows.

Lets understand the problem statement graphically and it will be more clear,

### Algorithm

Below Algorithm will only work for a Square Matrix that is having same number of Rows and Columns.

Transpose of given matrix can be obtained by changing its rows to columns and columns to rows.
1. Iterate through a Matrix and swap data of rows and columns.

2. While iterating make sure, Column start from where Row start.

### Java Program to find Transpose of Matrix In-place

```package matrix;

public class TransposeOfSquareMatrixInPlace {

public static void main(String[] args) {
new TransposeOfSquareMatrixInPlace();
}

public TransposeOfSquareMatrixInPlace() {
int[][] matrix = {
{1,  2,  3,  4,  5},
{6,  7,  8,  9,  10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};

System.out.println("Before Transpose");
printMatrix(matrix);

for (int i = 0; i < matrix.length; i++) {
for (int j = i; j < matrix[0].length; j++) {
int data = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = data;
}
}
System.out.println("\nAfter Transpose");
printMatrix(matrix);
}

private void printMatrix(int[][] matrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

```

### You may also like to see

#### How is ambiguous overloaded method call resolved in java

Enjoy !!!!

If you find any issue in post or face any error while implementing, Please comment.