Find the minimum difference path from ( 0 , 0 ) to ( N | JavaScript 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
let MAXI = 50 ; let dp = new Array ( MAXI ) ; let n , m ; let INT_MAX = Number . MAX_VALUE ; function minDifference ( x , y , k , b , c ) { if ( x >= n y >= m ) return INT_MAX ; if ( x == n - 1 && y == m - 1 ) { let diff = b [ x ] [ y ] - c [ x ] [ y ] ; return Math . min ( Math . abs ( k - diff ) , Math . abs ( k + diff ) ) ; } let ans = dp [ x ] [ y ] [ k ] ; if ( ans != - 1 ) return ans ; ans = INT_MAX ; let 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 ; } n = 2 ; m = 2 ; let b = [ [ 1 , 4 ] , [ 2 , 4 ] ] ; let c = [ [ 3 , 2 ] , [ 3 , 1 ] ] ; for ( let i = 0 ; i < MAXI ; i ++ ) { dp [ i ] = new Array ( MAXI ) ; for ( let j = 0 ; j < MAXI ; j ++ ) { dp [ i ] [ j ] = new Array ( MAXI * MAXI ) ; for ( let k = 0 ; k < MAXI * MAXI ; k ++ ) { dp [ i ] [ j ] [ k ] = - 1 ; } } } document . write ( minDifference ( 0 , 0 , 0 , b , c ) ) ;