Check if matrix can be converted to another matrix by transposing square sub | JavaScript 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
var n = 3 var m = 3 function check ( a , b ) { for ( var i = 0 ; i < n ; i ++ ) { var v1 = [ ] , v2 = [ ] ; var r = i ; var col = 0 ; while ( r >= 0 && col < m ) { v1 . push ( a [ r ] [ col ] ) ; v2 . push ( b [ r ] [ col ] ) ; r -- ; col ++ ; } v1 . sort ( ) ; v2 . sort ( ) ; for ( var i = 0 ; i < v1 . length ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } for ( var j = 1 ; j < m ; j ++ ) { var v1 = [ ] , v2 = [ ] ; var r = n - 1 ; var col = j ; while ( r >= 0 && col < m ) { v1 . push ( a [ r ] [ col ] ) ; v2 . push ( b [ r ] [ col ] ) ; r -- ; col ++ ; } v1 . sort ( ) ; v2 . sort ( ) ; for ( var i = 0 ; i < v1 . length ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } return true ; } var a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; var b = [ [ 1 , 4 , 7 ] , [ 2 , 5 , 6 ] , [ 3 , 8 , 9 ] ] ; if ( check ( a , b ) ) document . write ( " " ) ; else document . write ( " " ) ;