Function returns the total count
public static int CountWays ( int i , int j , int 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 ] ; }