Find minimum steps required to reach the end of a matrix | Set | Python3 program to implement above approach ; 2d array to store states of dp ; array to determine whether a state has been solved before ; Function to find the minimum number of steps to reach the end of matrix ; base cases ; if a state has been solved before it won 't be evaluated again. ; recurrence relation ; Driver Code
import numpy as np ; NEW_LINE n = 3 NEW_LINE dp = np . zeros ( ( n , n ) ) ; NEW_LINE v = np . zeros ( ( n , n ) ) ; NEW_LINE def minSteps ( i , j , arr ) : NEW_LINE INDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i > n - 1 or j > n - 1 ) : NEW_LINE INDENT return 9999999 ; NEW_LINE DEDENT if ( v [ i ] [ j ] ) : NEW_LINE INDENT return dp [ i ] [ j ] ; NEW_LINE DEDENT v [ i ] [ j ] = 1 ; NEW_LINE dp [ i ] [ j ] = 1 + min ( minSteps ( i + arr [ i ] [ j ] , j , arr ) , minSteps ( i , j + arr [ i ] [ j ] , arr ) ) ; NEW_LINE return dp [ i ] [ j ] ; NEW_LINE DEDENT arr = [ [ 2 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; NEW_LINE ans = minSteps ( 0 , 0 , arr ) ; NEW_LINE if ( ans >= 9999999 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT