Find minimum steps required to reach the end of a matrix | Set | Javascript 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
let n = 3 ; let dp = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { dp [ i ] = new Array ( n ) ; } let v = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { v [ i ] = new Array ( n ) ; } function minSteps ( i , j , arr ) { if ( i == n - 1 && j == n - 1 ) { return 0 ; } if ( i > n - 1 j > n - 1 ) { return 9999999 ; } if ( v [ i ] [ j ] == 1 ) { return dp [ i ] [ j ] ; } v [ i ] [ j ] = 1 ; dp [ i ] [ j ] = 1 + Math . min ( minSteps ( i + arr [ i ] [ j ] , j , arr ) , minSteps ( i , j + arr [ i ] [ j ] , arr ) ) ; return dp [ i ] [ j ] ; } let arr = [ [ 2 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; let ans = minSteps ( 0 , 0 , arr ) ; if ( ans >= 9999999 ) { document . write ( - 1 ) ; } else { document . write ( ans ) ; }