Count of ways to traverse a Matrix and return to origin in K steps | JavaScript program to count total number of ways to return to origin after completing given number of steps . ; Initialize [ , ] dp [ ] array with - 1 ; Function returns the total count ; Driver Program
var MOD = 1000000007 ; var dp = Array . from ( Array ( 101 ) , ( ) => Array ( 101 ) ) ; var N , M , K ; for ( var i = 0 ; i < 101 ; i ++ ) for ( var j = 0 ; j < 101 ; j ++ ) dp [ i ] [ j ] = new Array ( 101 ) . fill ( - 1 ) ; function CountWays ( i , j , k ) { if ( i >= N i < 0 j >= M j < 0 k < 0 ) return 0 ; if ( i == 0 && j == 0 && k == 0 ) return 1 ; if ( dp [ i ] [ j ] [ k ] != - 1 ) return dp [ i ] [ j ] [ k ] ; else dp [ i ] [ j ] [ k ] = ( CountWays ( i + 1 , j , k - 1 ) % MOD + CountWays ( i - 1 , j , k - 1 ) % MOD + CountWays ( i , j - 1 , k - 1 ) % MOD + CountWays ( i , j + 1 , k - 1 ) % MOD + CountWays ( i , j , k - 1 ) % MOD ) % MOD ; return dp [ i ] [ j ] [ k ] ; } N = 3 ; M = 3 ; K = 4 ; document . write ( CountWays ( 0 , 0 , K ) )