Swap upper and lower triangular halves of a given Matrix | C ++ program for the above approach ; Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diagonal ; If current element lies below the principal diagonal ; If current element lies above the principal diagonal ; Traverse again to swap values ; Find the index ; Principal diagonal ; Below main diagonal ; Above main diagonal ; Traverse the matrix and print ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ReverseSwap ( vector < vector < int > > & mat , int n ) { vector < int > lowerEle [ n ] ; vector < int > upperEle [ n ] ; int index ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { lowerEle [ index ] . push_back ( mat [ i ] [ j ] ) ; } else { upperEle [ index ] . push_back ( mat [ i ] [ j ] ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { mat [ i ] [ j ] = upperEle [ index ] . back ( ) ; upperEle [ index ] . pop_back ( ) ; } else { mat [ i ] [ j ] = lowerEle [ index ] . back ( ) ; lowerEle [ index ] . pop_back ( ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { vector < vector < int > > mat = { { 1 , 2 } , { 4 , 5 } } ; int N = mat . size ( ) ; ReverseSwap ( mat , N ) ; return 0 ; }