Find the minimum difference path from ( 0 , 0 ) to ( N | Java implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call
class GFG { final static int MAXI = 50 ; static int dp [ ] [ ] [ ] = new int [ MAXI ] [ MAXI ] [ MAXI * MAXI ] ; static int n , m ; final static int INT_MAX = Integer . MAX_VALUE ; static int minDifference ( int x , int y , int k , int b [ ] [ ] , int c [ ] [ ] ) { if ( x >= n y >= m ) return INT_MAX ; if ( x == n - 1 && y == m - 1 ) { int diff = b [ x ] [ y ] - c [ x ] [ y ] ; return Math . min ( Math . abs ( k - diff ) , Math . abs ( k + diff ) ) ; } int ans = dp [ x ] [ y ] [ k ] ; if ( ans != - 1 ) return ans ; ans = INT_MAX ; int diff = b [ x ] [ y ] - c [ x ] [ y ] ; ans = Math . min ( ans , minDifference ( x + 1 , y , Math . abs ( k + diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x , y + 1 , Math . abs ( k + diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x + 1 , y , Math . abs ( k - diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x , y + 1 , Math . abs ( k - diff ) , b , c ) ) ; return ans ; } public static void main ( String [ ] args ) { n = 2 ; m = 2 ; int b [ ] [ ] = { { 1 , 4 } , { 2 , 4 } } ; int c [ ] [ ] = { { 3 , 2 } , { 3 , 1 } } ; for ( int i = 0 ; i < MAXI ; i ++ ) { for ( int j = 0 ; j < MAXI ; j ++ ) { for ( int k = 0 ; k < MAXI * MAXI ; k ++ ) { dp [ i ] [ j ] [ k ] = - 1 ; } } } System . out . println ( minDifference ( 0 , 0 , 0 , b , c ) ) ; } }