In the Given Array n*n Matrix, return the Transpose Matrix
EX: matrix=[[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7], [2,5,8], [3,6,9]]
To transpose a matrix in Java, you can create a new matrix where the rows become columns and vice versa. Here’s a simple implementation:
public class TransposeMatrix {
public static int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] result = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] transposedMatrix = transpose(matrix);
printMatrix(transposedMatrix);
}
}