Minimum changes required to make each path in a matrix palindrome | Function for counting changes ; Maximum distance possible is ( n - 1 + m - 1 ) ; Stores the maximum element ; Update the maximum ; Stores frequencies of values for respective distances ; Initialize frequencies of cells as 0 ; Count frequencies of cell values in the matrix ; Increment frequency of value at distance i + j ; Store the most frequent value at i - th distance from ( 0 , 0 ) and ( N - 1 , M - 1 ) ; Calculate max frequency and total cells at distance i ; Count changes required to convert all cells at i - th distance to most frequent value ; Driver Code
function countChanges ( matrix , n , m ) { let i , j , dist = n + m - 1 ; let Max_element = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { Max_element = Math . max ( Max_element , matrix [ i ] [ j ] ) ; } } let freq = new Array ( dist ) ; for ( i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = new Array ( 2 ) ; } for ( i = 0 ; i < dist ; i ++ ) { for ( j = 0 ; j < Max_element + 1 ; j ++ ) freq [ i ] [ j ] = 0 ; } for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { freq [ i + j ] [ matrix [ i ] [ j ] ] ++ ; } } let min_changes_sum = 0 ; for ( i = 0 ; i < Math . floor ( dist / 2 ) ; i ++ ) { let maximum = 0 ; let total_values = 0 ; for ( j = 0 ; j < Max_element + 1 ; j ++ ) { maximum = Math . max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) ; total_values += freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ; } min_changes_sum += total_values - maximum ; } return min_changes_sum ; } let mat = [ [ 7 , 0 , 3 , 1 , 8 , 1 , 3 ] , [ 0 , 4 , 0 , 1 , 0 , 4 , 0 ] , [ 3 , 1 , 8 , 3 , 1 , 0 , 7 ] ] ; let minChanges = countChanges ( mat , 3 , 7 ) ; document . write ( minChanges ) ;