Minimum steps to reach any of the boundary edges of a matrix | Set 1 | Javascript program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertically up ; horizontally right ; horizontally left ; vertically down ; minimum of every path ; Function that returns the minimum steps ; index to store the location at which you are standing ; find '2' in the matrix ; Initialize dp matrix with - 1 ; Initialize vis matrix with false ; Call function to find out minimum steps using memoization and recursion ; if not possible ; Driver Code
let r = 4 , c = 5 ; function findMinSteps ( mat , n , m , dp , vis ) { if ( n == 0 || m == 0 || n == ( r - 1 ) || m == ( c - 1 ) ) { return 0 ; } if ( dp [ n ] [ m ] != - 1 ) return dp [ n ] [ m ] ; vis [ n ] [ m ] = true ; let ans1 , ans2 , ans3 , ans4 ; ans1 = ans2 = ans3 = ans4 = 1e9 ; if ( mat [ n - 1 ] [ m ] == 0 ) { if ( ! vis [ n - 1 ] [ m ] ) ans1 = 1 + findMinSteps ( mat , n - 1 , m , dp , vis ) ; } if ( mat [ n ] [ m + 1 ] == 0 ) { if ( ! vis [ n ] [ m + 1 ] ) ans2 = 1 + findMinSteps ( mat , n , m + 1 , dp , vis ) ; } if ( mat [ n ] [ m - 1 ] == 0 ) { if ( ! vis [ n ] [ m - 1 ] ) ans3 = 1 + findMinSteps ( mat , n , m - 1 , dp , vis ) ; } if ( mat [ n + 1 ] [ m ] == 0 ) { if ( ! vis [ n + 1 ] [ m ] ) ans4 = 1 + findMinSteps ( mat , n + 1 , m , dp , vis ) ; } dp [ n ] [ m ] = Math . min ( ans1 , Math . min ( ans2 , Math . min ( ans3 , ans4 ) ) ) ; return dp [ n ] [ m ] ; } function minimumSteps ( mat , n , m ) { let twox = - 1 ; let twoy = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 2 ) { twox = i ; twoy = j ; break ; } } if ( twox != - 1 ) break ; } let dp = new Array ( r ) ; for ( let j = 0 ; j < r ; j ++ ) { dp [ j ] = new Array ( r ) ; for ( let i = 0 ; i < r ; i ++ ) { dp [ j ] [ i ] = - 1 ; } } let vis = new Array ( r ) ; for ( let j = 0 ; j < r ; j ++ ) { vis [ j ] = new Array ( r ) ; for ( let i = 0 ; i < r ; i ++ ) { vis [ j ] [ i ] = false ; } } let res = findMinSteps ( mat , twox , twoy , dp , vis ) ; if ( res >= 1e9 ) return - 1 ; else return res ; } let mat = [ [ 1 , 1 , 1 , 0 , 1 ] , [ 1 , 0 , 2 , 0 , 1 ] , [ 0 , 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 0 ] ] ; document . write ( minimumSteps ( mat , r , c ) ) ;