Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Java implementation to find the minimum number of changes required such that every path from top left to the bottom right are palindromic paths ; Function to find the minimum number of the changes required for the every path to be palindromic ; count variable for maintaining total changes . ; left and right variables for keeping distance values from cell ( 0 , 0 ) and ( N - 1 , M - 1 ) respectively . ; Iterating over the matrix ; Finding minimum number of changes required . ; Minimum no . of changes will be the the minimum no . of different values and we will assume to make them equals to value with maximum frequency element ; Moving ahead with greater distance ; Driver Code ; Function Call
import java . io . * ; import java . util . * ; class GFG { static final int M = 3 ; static final int N = 3 ; static int minchanges ( int [ ] [ ] mat ) { int count = 0 ; int left = 0 , right = N + M - 2 ; while ( left < right ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; int totalsize = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + j == left ) { mp . put ( mat [ i ] [ j ] , mp . getOrDefault ( mat [ i ] [ j ] , 0 ) + 1 ) ; totalsize ++ ; } else if ( i + j == right ) { mp . put ( mat [ i ] [ j ] , mp . getOrDefault ( mat [ i ] [ j ] , 0 ) + 1 ) ; totalsize ++ ; } } } int changes = 0 ; for ( Map . Entry < Integer , Integer > itr : mp . entrySet ( ) ) changes = Math . max ( changes , itr . getValue ( ) ) ; count += totalsize - changes ; left ++ ; right -- ; } return count ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 4 , 1 } , { 2 , 5 , 3 } , { 1 , 3 , 1 } } ; System . out . println ( minchanges ( mat ) ) ; } }