Minimum cost path in a Matrix by moving only on value difference of X | Java 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
import java . lang . * ; import java . util . * ; class GFG { static final long MAX = ( long ) 1e18 ; static long n , m ; static List < List < Long > > v = new ArrayList < > ( 151 ) ; static long [ ] [ ] dp = new long [ 151 ] [ 151 ] ; static long min_operation ( long i , long j , long val , long x ) { if ( i == n - 1 && j == m - 1 ) { if ( val > v . get ( ( int ) i ) . get ( ( int ) j ) ) { return dp [ ( int ) i ] [ ( int ) j ] = MAX ; } else { return dp [ ( int ) i ] [ ( int ) j ] = v . get ( ( int ) i ) . get ( ( int ) j ) - val ; } } if ( i == n j == m ) { return dp [ ( int ) i ] [ ( int ) j ] = MAX ; } if ( dp [ ( int ) i ] [ ( int ) j ] != - 1 ) { return dp [ ( int ) i ] [ ( int ) j ] ; } if ( val > v . get ( ( int ) i ) . get ( ( int ) j ) ) { return dp [ ( int ) i ] [ ( int ) j ] = MAX ; } long tmp = v . get ( ( int ) i ) . get ( ( int ) j ) - val ; tmp += Math . min ( min_operation ( i + 1 , j , val + x , x ) , min_operation ( i , j + 1 , val + x , x ) ) ; return dp [ ( int ) i ] [ ( int ) j ] = tmp ; } static long solve ( long x ) { long ans = Long . MAX_VALUE ; for ( long i = 0 ; i < n ; i ++ ) { for ( long j = 0 ; j < m ; j ++ ) { long val = v . get ( ( int ) i ) . get ( ( int ) j ) - x * ( i + j ) ; for ( int k = 0 ; k < dp . length ; k ++ ) for ( int l = 0 ; l < dp [ k ] . length ; l ++ ) dp [ k ] [ l ] = - 1 ; val = min_operation ( 0l , 0l , val , x ) ; ans = Math . min ( ans , val ) ; } } return ans ; } public static void main ( String [ ] args ) { n = 2 ; m = 2 ; long x = 3 ; v . add ( Arrays . asList ( 15l , 153l ) ) ; v . add ( Arrays . asList ( 135l , 17l ) ) ; System . out . println ( solve ( x ) ) ; } }