Check if matrix can be converted to another matrix by transposing square sub | Python 3 implementation of the approach ; Function that returns true if matrix1 can be converted to matrix2 with the given operation ; Traverse all the diagonals starting at first column ; Traverse in diagonal ; Store the diagonal elements ; Move up ; Sort the elements ; Check if they are same ; Traverse all the diagonals starting at last row ; Traverse in the diagonal ; Store diagonal elements ; Sort all elements ; Check for same ; If every element matches ; Driver code
n = 3 NEW_LINE m = 3 NEW_LINE def check ( a , b ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE r = i NEW_LINE col = 0 NEW_LINE while ( r >= 0 and col < m ) : NEW_LINE INDENT v1 . append ( a [ r ] [ col ] ) NEW_LINE v2 . append ( b [ r ] [ col ] ) NEW_LINE r -= 1 NEW_LINE col += 1 NEW_LINE DEDENT v1 . sort ( reverse = False ) NEW_LINE v2 . sort ( reverse = False ) NEW_LINE for i in range ( len ( v1 ) ) : NEW_LINE INDENT if ( v1 [ i ] != v2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT for j in range ( 1 , m ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE r = n - 1 NEW_LINE col = j NEW_LINE while ( r >= 0 and col < m ) : NEW_LINE INDENT v1 . append ( a [ r ] [ col ] ) NEW_LINE v2 . append ( b [ r ] [ col ] ) NEW_LINE r -= 1 NEW_LINE col += 1 NEW_LINE DEDENT v1 . sort ( reverse = False ) NEW_LINE v2 . sort ( reverse = False ) NEW_LINE for i in range ( len ( v1 ) ) : NEW_LINE INDENT if ( v1 [ i ] != v2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE b = [ [ 1 , 4 , 7 ] , [ 2 , 5 , 6 ] , [ 3 , 8 , 9 ] ] NEW_LINE if ( check ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT