Find the minimum difference path from ( 0 , 0 ) to ( N | Python3 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
import numpy as np NEW_LINE import sys NEW_LINE MAXI = 50 NEW_LINE INT_MAX = sys . maxsize NEW_LINE dp = np . ones ( ( MAXI , MAXI , MAXI * MAXI ) ) ; NEW_LINE dp *= - 1 NEW_LINE def minDifference ( x , y , k , b , c ) : NEW_LINE INDENT if ( x >= n or y >= m ) : NEW_LINE INDENT return INT_MAX ; NEW_LINE DEDENT if ( x == n - 1 and y == m - 1 ) : NEW_LINE INDENT diff = b [ x ] [ y ] - c [ x ] [ y ] ; NEW_LINE return min ( abs ( k - diff ) , abs ( k + diff ) ) ; NEW_LINE DEDENT ans = dp [ x ] [ y ] [ k ] ; NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT ans = INT_MAX ; NEW_LINE diff = b [ x ] [ y ] - c [ x ] [ y ] ; NEW_LINE ans = min ( ans , minDifference ( x + 1 , y , abs ( k + diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x , y + 1 , abs ( k + diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x + 1 , y , abs ( k - diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x , y + 1 , abs ( k - diff ) , b , c ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; m = 2 ; b = [ [ 1 , 4 ] , [ 2 , 4 ] ] ; NEW_LINE c = [ [ 3 , 2 ] , [ 3 , 1 ] ] ; NEW_LINE print ( minDifference ( 0 , 0 , 0 , b , c ) ) ; NEW_LINE DEDENT