Minimum cells required to reach destination with jumps equal to cell values | Javascript implementation to count minimum cells required to be covered to reach destination ; function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; initially no cells can be reached ; base case ; building up the dp [ ] [ ] matrix ; dp [ i ] [ j ] != LET_MAX denotes that cell ( i , j ) can be reached from cell ( 0 , 0 ) and the other half of the condition finds the cell on the right that can be reached from ( i , j ) ; the other half of the condition finds the cell right below that can be reached from ( i , j ) ; it true then cell ( m - 1 , n - 1 ) can be reached from cell ( 0 , 0 ) and returns the minimum number of cells covered ; cell ( m - 1 , n - 1 ) cannot be reached from cell ( 0 , 0 ) ; driver function
let SIZE = 100 ; function minCells ( mat , m , n ) { let dp = new Array ( m ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < m ; i ++ ) for ( let j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = Number . MAX_VALUE ; dp [ 0 ] [ 0 ] = 1 ; for ( let i = 0 ; i < m ; i ++ ) { for ( let j = 0 ; j < n ; j ++ ) { if ( dp [ i ] [ j ] != Number . MAX_VALUE && ( j + mat [ i ] [ j ] ) < n && ( dp [ i ] [ j ] + 1 ) < dp [ i ] [ j + mat [ i ] [ j ] ] ) dp [ i ] [ j + mat [ i ] [ j ] ] = dp [ i ] [ j ] + 1 ; if ( dp [ i ] [ j ] != Number . MAX_VALUE && ( i + mat [ i ] [ j ] ) < m && ( dp [ i ] [ j ] + 1 ) < dp [ i + mat [ i ] [ j ] ] [ j ] ) dp [ i + mat [ i ] [ j ] ] [ j ] = dp [ i ] [ j ] + 1 ; } } if ( dp [ m - 1 ] [ n - 1 ] != Number . MAX_VALUE ) return dp [ m - 1 ] [ n - 1 ] ; return - 1 ; } let mat = [ [ 2 , 3 , 2 , 1 , 4 ] , [ 3 , 2 , 5 , 8 , 2 ] , [ 1 , 1 , 2 , 2 , 1 ] ] ; let m = 3 , n = 5 ; document . write ( " " + " " + minCells ( mat , m , n ) ) ;