Minimum cost path in a Matrix by moving only on value difference of X | C # 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
using System ; using System . Collections . Generic ; class GFG { static long MAX = ( long ) 1e18 ; static long n , m ; static List < List < long > > v = new List < List < long > > ( ) ; 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 [ ( int ) i ] [ ( int ) j ] ) { return dp [ ( int ) i , ( int ) j ] = MAX ; } else { return dp [ ( int ) i , ( int ) j ] = v [ ( int ) i ] [ ( 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 [ ( int ) i ] [ ( int ) j ] ) { return dp [ ( int ) i , ( int ) j ] = MAX ; } long temp = v [ ( int ) i ] [ ( int ) j ] - val ; temp += Math . Min ( min_operation ( i + 1 , j , val + x , x ) , min_operation ( i , j + 1 , val + x , x ) ) ; return dp [ ( int ) i , ( int ) j ] = temp ; } static long solve ( long x ) { long ans = Int64 . MaxValue ; for ( long i = 0 ; i < n ; i ++ ) { for ( long j = 0 ; j < m ; j ++ ) { long val = v [ ( int ) i ] [ ( int ) j ] - x * ( i + j ) ; for ( long k = 0 ; k < dp . GetLength ( 0 ) ; k ++ ) { for ( long l = 0 ; l < dp . GetLength ( 1 ) ; l ++ ) { dp [ k , l ] = - 1 ; } } val = min_operation ( 0 , 0 , val , x ) ; ans = Math . Min ( ans , val ) ; } } return ans ; } static public void Main ( ) { for ( int i = 0 ; i < 151 ; i ++ ) { v . Add ( new List < long > ( ) ) ; v [ i ] . Add ( 0 ) ; v [ i ] . Add ( 0 ) ; } v [ 0 ] [ 0 ] = 15 ; v [ 0 ] [ 1 ] = 153 ; v [ 1 ] [ 0 ] = 135 ; v [ 1 ] [ 1 ] = 17 ; n = 2 ; m = 2 ; long x = 3 ; Console . WriteLine ( solve ( x ) ) ; } }