forked from ghostmkg/dsa-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransposeOfMatrix.java
More file actions
48 lines (38 loc) · 1.28 KB
/
TransposeOfMatrix.java
File metadata and controls
48 lines (38 loc) · 1.28 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Time Complexity: O(m * n)
// Space Complexity: O(m * n)
import java.util.Scanner;
public class MatrixTranspose {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input number of rows and columns
System.out.print("Enter number of rows (m): ");
int m = sc.nextInt();
System.out.print("Enter number of columns (n): ");
int n = sc.nextInt();
int[][] matrix = new int[m][n];
// Input matrix elements
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
// Compute transpose
int[][] transpose = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Swap rows with columns
transpose[j][i] = matrix[i][j];
}
}
// Display transposed matrix
System.out.println("\nTransposed Matrix (" + n + " x " + m + "):");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}