Posts Transpose of a Matrix
Post
Cancel

Transpose of a Matrix

PROBLEM DESCRIPTION

Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.

geeksforgeeks

SOLUTION

The main observation is that, if we can every element A[i][j] with A[j][i], we get the transpose of the matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution
{
    //Function to find transpose of a matrix.
    static void transpose(int matrix[][], int n)
    {
        
        for(int i=0; i<n; i++){
            for(int j=i; j<n; j++){
                swap(i, j, matrix);
            }
        }
        
    }
    
    static void swap(int i, int j, int[][] matrix){
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }
}
This post is licensed under CC BY 4.0 by the author.