Minimum cost path in a Matrix by moving only on value difference of X | Javascript implementation to find the minimum number of operations required to move from ( 1 , 1 ) to ( N , M ) ; Function to find the minimum operations required to move to bottom - right cell of matrix ; Condition to check if the current cell is the bottom - right cell of the matrix ; Condition to check if the current cell is out of matrix ; Condition to check if the current indices is already computed ; Condition to check that the movement with the current value is not possible ; Recursive call to compute the number of operation required to compute the value ; Function to find the minimum number of operations required to reach the bottom - right cell ; Loop to iterate over every possible cell of the matrix ; Driver Code ; Function call
let MAX = 1e18 ; let n , m ; let v = new Array ( 151 ) ; for ( let i = 0 ; i < 151 ; i ++ ) { v [ i ] = [ 0 , 0 ] ; } let dp = new Array ( 151 ) ; for ( let i = 0 ; i < 151 ; i ++ ) { dp [ i ] = new Array ( 151 ) ; } function min_operation ( i , j , val , x ) { if ( i == n - 1 && j == m - 1 ) { if ( val > v [ i ] [ j ] ) { return dp [ i ] [ j ] = MAX ; } else { return dp [ i ] [ j ] = v [ i ] [ j ] - val ; } } if ( i == n j == m ) { return dp [ i ] [ j ] = MAX ; } if ( dp [ i ] [ j ] != - 1 ) { return dp [ i ] [ j ] ; } if ( val > v [ i ] [ j ] ) { return dp [ i ] [ j ] = MAX ; } let tmp = v [ i ] [ j ] - val ; tmp += Math . min ( min_operation ( i + 1 , j , val + x , x ) , min_operation ( i , j + 1 , val + x , x ) ) ; return dp [ i ] [ j ] = tmp ; } function solve ( x ) { let ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { let val = v [ i ] [ j ] - x * ( i + j ) ; for ( let k = 0 ; k < dp . length ; k ++ ) for ( let l = 0 ; l < dp [ k ] . length ; l ++ ) dp [ k ] [ l ] = - 1 ; val = min_operation ( 0 , 0 , val , x ) ; ans = Math . min ( ans , val ) ; } } return ans ; } let x = 3 ; n = 2 ; m = 2 ; v [ 0 ] = [ 15 , 153 ] ; v [ 1 ] = [ 135 , 17 ] ; document . write ( solve ( x ) + " " ) ;