text: Minimum steps to convert all top left to bottom right paths in Matrix as palindrome | Set 2 | Function for counting minimum number of changes ; Distance of elements from ( 0 , 0 ) will is i range [ 0 , n + m - 2 ] ; Store frequencies of [ 0 , 9 ] at distance i Initialize all with zero ; Count frequencies of [ 0 , 9 ] ; Increment frequency of value matrix [ i ] [ j ] at distance i + j ; Find value with max frequency and count total cells at distance i from front end and rear end ; Change all values to the value with max frequency ; Return the answer ; Driver code ; Given matrix ; Function call
code: def countChanges ( matrix , n , m ) : NEW_LINE INDENT dist = n + m - 1 NEW_LINE freq = [ [ 0 ] * 10 for i in range ( dist ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT freq [ i + j ] [ matrix [ i ] [ j ] ] += 1 NEW_LINE DEDENT DEDENT min_changes_sum = 0 NEW_LINE for i in range ( dist // 2 ) : NEW_LINE INDENT maximum = 0 NEW_LINE total_values = 0 NEW_LINE for j in range ( 10 ) : NEW_LINE INDENT maximum = max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE total_values += ( freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE DEDENT min_changes_sum += ( total_values - maximum ) NEW_LINE DEDENT return min_changes_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 ] , [ 3 , 5 ] ] NEW_LINE print ( countChanges ( mat , 2 , 2 ) ) NEW_LINE DEDENT