Check if matrix can be converted to another matrix by transposing square sub | Java 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
import java . util . * ; class GFG { static final int n = 3 ; static final int m = 3 ; static boolean check ( int a [ ] [ ] , int b [ ] [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { Vector < Integer > v1 = new Vector < Integer > ( ) ; Vector < Integer > v2 = new Vector < Integer > ( ) ; int r = i ; int col = 0 ; while ( r >= 0 && col < m ) { v1 . add ( a [ r ] [ col ] ) ; v2 . add ( b [ r ] [ col ] ) ; r -- ; col ++ ; } Collections . sort ( v1 ) ; Collections . sort ( v2 ) ; for ( int j = 0 ; j < v1 . size ( ) ; j ++ ) { if ( v1 . get ( j ) != v2 . get ( j ) ) { return false ; } } } for ( int j = 1 ; j < m ; j ++ ) { Vector < Integer > v1 = new Vector < Integer > ( ) ; Vector < Integer > v2 = new Vector < Integer > ( ) ; int r = n - 1 ; int col = j ; while ( r >= 0 && col < m ) { v1 . add ( a [ r ] [ col ] ) ; v2 . add ( b [ r ] [ col ] ) ; r -- ; col ++ ; } Collections . sort ( v1 ) ; Collections . sort ( v2 ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) { if ( v1 . get ( i ) != v2 . get ( i ) ) { return false ; } } } return true ; } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int b [ ] [ ] = { { 1 , 4 , 7 } , { 2 , 5 , 6 } , { 3 , 8 , 9 } } ; if ( check ( a , b ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }