-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransposeMatrix.java
More file actions
33 lines (29 loc) · 907 Bytes
/
Copy pathTransposeMatrix.java
File metadata and controls
33 lines (29 loc) · 907 Bytes
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
26
27
28
29
30
31
32
33
public class TransposeMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("Original Matrix:");
printMatrix(matrix);
int[][] transposed = transpose(matrix);
System.out.println("Transposed Matrix:");
printMatrix(transposed);
}
static int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
}
}