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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minchanges ( vector < vector < int > > mat ) { int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; int i , j , ans = 0 , x ; map < int , int > mp ; for ( i = 0 ; i < N / 2 ; i ++ ) { for ( j = 0 ; j < M / 2 ; j ++ ) { mp [ mat [ i ] [ M - 1 - j ] ] ++ ; mp [ mat [ i ] [ j ] ] ++ ; mp [ mat [ N - 1 - i ] [ M - 1 - j ] ] ++ ; mp [ mat [ N - 1 - i ] [ j ] ] ++ ; x = 0 ; for ( auto it = mp . begin ( ) ; it != mp . end ( ) ; it ++ ) { x = max ( x , it -> second ) ; } 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 ++ ; } } cout << ans ; } int main ( ) { vector < vector < int > > mat { { 1 , 2 , 3 } , { 4 , 5 , 3 } , { 1 , 2 , 1 } } ; minchanges ( mat ) ; }