Minimum replacements required to make given Matrix palindromic | 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 ; Prminimum changes ; Given matrix ; Function Call
def minchanges ( mat ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE ans = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT for j in range ( M // 2 ) : NEW_LINE INDENT mp [ mat [ i ] [ M - 1 - j ] ] = mp . get ( mat [ i ] [ M - 1 - j ] , 0 ) + 1 NEW_LINE mp [ mat [ i ] [ j ] ] = mp . get ( mat [ i ] [ j ] , 0 ) + 1 NEW_LINE mp [ mat [ N - 1 - i ] [ M - 1 - j ] ] = mp . get ( mat [ N - 1 - i ] [ M - 1 - j ] , 0 ) + 1 NEW_LINE mp [ mat [ N - 1 - i ] [ j ] ] = mp . get ( mat [ N - 1 - i ] [ j ] , 0 ) + 1 NEW_LINE x = 0 NEW_LINE for it in mp : NEW_LINE INDENT x = max ( x , mp [ it ] ) NEW_LINE DEDENT ans = ans + 4 - x NEW_LINE mp . clear ( ) NEW_LINE DEDENT DEDENT if ( N % 2 == 1 ) : NEW_LINE INDENT for i in range ( M // 2 ) : NEW_LINE INDENT if ( mat [ N // 2 ] [ i ] != mat [ N // 2 ] [ M - 1 - i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT if ( M % 2 == 1 ) : NEW_LINE INDENT for i in range ( N // 2 ) : NEW_LINE INDENT if ( mat [ i ] [ M // 2 ] != mat [ N - 1 - i ] [ M // 2 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 3 ] , [ 1 , 2 , 1 ] ] NEW_LINE minchanges ( mat ) NEW_LINE