Minimum replacements required to make given Matrix palindromic | Java program for the above approach ; Function to count minimum changes to make the matrix palindromic ; Rows in the matrix ; Columns in the matrix ; Traverse the given matrix ; Store the frequency of the four cells ; Iterate over the map ; Min changes to do to make all ; Four elements equal ; Make the middle row palindromic ; Make the middle column palindromic ; Print minimum changes ; Driver Code ; Given matrix ; Function Call
import java . util . * ; class GFG { static void minchanges ( int [ ] [ ] mat ) { int N = mat . length ; int M = mat [ 0 ] . length ; int i , j , ans = 0 , x ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( i = 0 ; i < N / 2 ; i ++ ) { for ( j = 0 ; j < M / 2 ; j ++ ) { if ( mp . containsKey ( mat [ i ] [ M - 1 - j ] ) ) { mp . put ( mat [ i ] [ M - 1 - j ] , mp . get ( mat [ i ] [ M - 1 - j ] ) + 1 ) ; } else { mp . put ( mat [ i ] [ M - 1 - j ] , 1 ) ; } if ( mp . containsKey ( mat [ i ] [ j ] ) ) { mp . put ( mat [ i ] [ j ] , mp . get ( mat [ i ] [ j ] ) + 1 ) ; } else { mp . put ( mat [ i ] [ j ] , 1 ) ; } if ( mp . containsKey ( mat [ N - 1 - i ] [ M - 1 - j ] ) ) { mp . put ( mat [ N - 1 - i ] [ M - 1 - j ] , mp . get ( mat [ N - 1 - i ] [ M - 1 - j ] ) + 1 ) ; } else { mp . put ( mat [ N - 1 - i ] [ M - 1 - j ] , 1 ) ; } if ( mp . containsKey ( mat [ N - 1 - i ] [ j ] ) ) { mp . put ( mat [ N - 1 - i ] [ j ] , mp . get ( mat [ N - 1 - i ] [ j ] ) + 1 ) ; } else { mp . put ( mat [ N - 1 - i ] [ j ] , 1 ) ; } x = 0 ; for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { x = Math . max ( x , it . getValue ( ) ) ; } ans = ans + 4 - x ; mp . clear ( ) ; } } if ( N % 2 == 1 ) { for ( i = 0 ; i < M / 2 ; i ++ ) { if ( mat [ N / 2 ] [ i ] != mat [ N / 2 ] [ M - 1 - i ] ) ans ++ ; } } if ( M % 2 == 1 ) { for ( i = 0 ; i < N / 2 ; i ++ ) { if ( mat [ i ] [ M / 2 ] != mat [ N - 1 - i ] [ M / 2 ] ) ans ++ ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 3 } , { 1 , 2 , 1 } } ; minchanges ( mat ) ; } }