Minimum replacements required to make given Matrix palindromic | C # 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
using System ; using System . Collections . Generic ; class GFG { static void minchanges ( int [ , ] mat ) { int N = mat . GetLength ( 0 ) ; int M = mat . GetLength ( 1 ) ; int i , j , ans = 0 , x ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( i = 0 ; i < N / 2 ; i ++ ) { for ( j = 0 ; j < M / 2 ; j ++ ) { if ( mp . ContainsKey ( mat [ i , M - 1 - j ] ) ) { mp [ mat [ i , M - 1 - j ] ] = mp [ mat [ i , M - 1 - j ] ] + 1 ; } else { mp . Add ( mat [ i , M - 1 - j ] , 1 ) ; } if ( mp . ContainsKey ( mat [ i , j ] ) ) { mp [ mat [ i , j ] ] = mp [ mat [ i , j ] ] + 1 ; } else { mp . Add ( mat [ i , j ] , 1 ) ; } if ( mp . ContainsKey ( mat [ N - 1 - i , M - 1 - j ] ) ) { mp [ mat [ N - 1 - i , M - 1 - j ] ] = mp [ mat [ N - 1 - i , M - 1 - j ] ] + 1 ; } else { mp . Add ( mat [ N - 1 - i , M - 1 - j ] , 1 ) ; } if ( mp . ContainsKey ( mat [ N - 1 - i , j ] ) ) { mp [ mat [ N - 1 - i , j ] ] = mp [ mat [ N - 1 - i , j ] ] + 1 ; } else { mp . Add ( mat [ N - 1 - i , j ] , 1 ) ; } x = 0 ; foreach ( KeyValuePair < int , int > it in mp ) { x = Math . Max ( x , it . Value ) ; } 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 ++ ; } } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { int [ , ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 3 } , { 1 , 2 , 1 } } ; minchanges ( mat ) ; } }