Transpose of a Matrix
Send Feedback
Code Genius is an all-in-one platform for bloggers, YouTubers, job seekers, and tech enthusiasts. It offers resources on content creation, job search, cooling pads, latest tech info, smartphones, headphones, laptops, electronics, and online earning.
Transpose of a Matrix
Let matrix be :
1 2
3 4
Then transpose of the matrix will be:
1 3
2 4
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘M’ and ‘N’, representing the size of the matrices.
The next ‘M’ lines of each test case contain ‘N’ space-separated integers, representing the elements of ‘MAT’.
For each test case, print the transpose of the matrix.
Print output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= M, N <= 3*10^3
0 <= MAT[i][j] <= 10^7
Time Limit: 1 sec
2
2 2
1 2
3 4
3 2
1 2
2 3
3 4
1 3
2 4
1 2 3
2 3 4
For test case 1:
The transpose of the matrix will be:
1 3
2 4
For test case 2:
The transpose of the matrix will be:
1 2 3
2 3 4
2
2 3
1 2 3
3 4 5
2 1
1
2
1 3
2 4
3 5
1 2
code for this
import java.util.*;import java.io.*;
public class Solution {
public static int[][] transpose(int m, int n, int[][] mat) { int[][] result = new int[n][m];
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { result[j][i] = mat[i][j]; } }
return result; }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt();
for (int t = 0; t < T; t++) { int M = scanner.nextInt(); int N = scanner.nextInt(); int[][] MAT = new int[M][N];
for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { MAT[i][j] = scanner.nextInt(); } }
int[][] transposedMatrix = transpose(M, N, MAT);
for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { System.out.print(transposedMatrix[i][j] + " "); } System.out.println(); } } }}
Comments
Post a Comment