Check if matrix can be converted to another matrix by transposing square sub | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define n  3 NEW_LINE #define m  3 NEW_LINE bool check ( int a [ n ] [ m ] , int b [ n ] [ m ] ) { for ( int i = 0 ; i < n ; i ++ ) { vector < int > v1 , v2 ; int r = i ; int col = 0 ; while ( r >= 0 && col < m ) { v1 . push_back ( a [ r ] [ col ] ) ; v2 . push_back ( b [ r ] [ col ] ) ; r -- ; col ++ ; } sort ( v1 . begin ( ) , v1 . end ( ) ) ; sort ( v2 . begin ( ) , v2 . end ( ) ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } for ( int j = 1 ; j < m ; j ++ ) { vector < int > v1 , v2 ; int r = n - 1 ; int col = j ; while ( r >= 0 && col < m ) { v1 . push_back ( a [ r ] [ col ] ) ; v2 . push_back ( b [ r ] [ col ] ) ; r -- ; col ++ ; } sort ( v1 . begin ( ) , v1 . end ( ) ) ; sort ( v2 . begin ( ) , v2 . end ( ) ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } return true ; } int main ( ) { int a [ n ] [ m ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int b [ n ] [ m ] = { { 1 , 4 , 7 } , { 2 , 5 , 6 } , { 3 , 8 , 9 } } ; if ( check ( a , b ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }