Write a program to find the transpose of a given matrix.
Example 1:
Input:arr[3][3]={{6,2,3},{4,3,2},{4,5,7}}
Output:arr[3][3]={{6,4,4},{2,3,5},{3,2,7}}
Approach
C
#include <stdio.h>//Function to find the transpose of matrixvoid transposeMatix(int matrixA[][3], int n, int m){int matrixB[m][n];for (int i = 0; i < n; i++){for (int j = 0; j < m; j++)matrixB[j][i] = matrixA[i][j];}for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){printf("%d ", matrixB[i][j]);}printf("\n");}}int main(){//matrix inputint matrxixA[][3] = {{6, 2, 3}, {4, 3, 2}, {4, 5, 7}};int n = 3, m = 3;transposeMatix(matrxixA, n, m);}//Time Complexity: O(n^2)//Space Complexity: O(n^2)
Java
public class MatrixTranspose {public static void main(String[] args) {// matrix inputint matrxixA[][] = { { 6, 2, 3 },{ 4, 3, 2 }, { 4, 5, 7 } };// row, colint n = 3, m = 3;// transpose matrixint matrixB[][] = transposeMatix(matrxixA, n, m);// print after transposeprintMatrix(matrixB);}private static void printMatrix(int[][] matrixA) {for (int i = 0; i < matrixA.length; i++) {for (int j = 0; j < matrixA.length; j++) {System.out.print(matrixA[i][j] + " ");}System.out.println();}}private static int[][] transposeMatix(int[][] matrxixA,int n, int m) {// create new matrix of m,nint matrixB[][] = new int[m][n];for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {// put value in new matrixmatrixB[j][i] = matrxixA[i][j];}}return matrixB;}}//Time Complexity: O(n^2)//Space Complexity: O(n^2)
C++
#include <bits/stdc++.h>using namespace std;//Function to find the transpose of matrixvoid transposeMatix(int matrixA[][3],int n,int m){int matrixB[m][n];for(int i=0;i<n;i++){for(int j=0;j<m;j++)matrixB[j][i]=matrixA[i][j];}for(int i=0;i<m;i++){for(int j=0;j<n;j++)cout<<matrixB[i][j]<<" ";cout<<"\n";}}int main(){//matrix inputint matrxixA[][3]={{6,2,3},{4,3,2},{4,5,7}};int n=3,m=3;transposeMatix(matrxixA,n,m);}//Time Complexity: O(n^2)//Space Complexity: O(n^2)
No comments:
Post a Comment