Swap upper and lower triangular halves of a given Matrix | 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 pr ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves
def ReverseSwap ( mat , n ) : NEW_LINE INDENT lowerEle = [ [ ] for i in range ( n ) ] NEW_LINE upperEle = [ [ ] for i in range ( n ) ] NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT index = abs ( i - j ) NEW_LINE if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( j < i ) : NEW_LINE INDENT lowerEle [ index ] . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT upperEle [ index ] . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT index = abs ( i - j ) NEW_LINE if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( j < i ) : NEW_LINE INDENT mat [ i ] [ j ] = upperEle [ index ] [ - 1 ] NEW_LINE del upperEle [ index ] [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = lowerEle [ index ] [ - 1 ] NEW_LINE del lowerEle [ index ] [ - 1 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 ] , [ 4 , 5 ] ] NEW_LINE N = len ( mat ) NEW_LINE ReverseSwap ( mat , N ) NEW_LINE DEDENT