Grid Walking


Problem Statement :


You are situated in an n dimensional grid at position (x[1],x[2],...,x[n]). The dimensions of the grid are D[1],D[2],...,D[n]). In one step, you can walk one step ahead or behind in any one of the n dimensions. This implies that there are always 2*n possible moves if movements are unconstrained by grid boundaries. How many ways can you take m steps without leaving the grid at any point? You leave the grid if at any point x[i], either x[i] <= 0 or x[i] >D[i].

For example, you start off in a 3 dimensional grid at position x = [2,2,2]. The dimensions of the grid are D = [3,3,3], so each of your axes will be numbered from 1 to 3. If you want to move m =1 step, you can move to the following coordinates: {[1,2,2],[2,1,2],[2,2,1],[3,2,2],[2,3,2],[2,2,3]}.

image
If we started at x=[1,1,1] in the same grid, our new paths would lead to {[1,1,2],[1,2,1],[2,1,1]}. Other moves are constrained by x[i] !<= 0.

Function Description

Complete the gridWalking function in the editor below. It should return an integer that represents the number of possible moves, modulo (10^9+7).

gridWalking has the following parameter(s):

m: an integer that represents the number of steps
x: an integer array where each x[i] represents a coordinate in the ith dimension where 1 <= i <=n
D: an integer array where each D[i] represents the upper limit of the axis in the ith dimension
Input Format 

The first line contains an integer t, the number of test cases.

Each of the next t sets of lines is as follows:

The first line contains two space-separated integers, n and m.
The next line contains n space-separated integers x[i].
The third line of each test contains n space-separated integers D[i].

Constraints
1 <= t <= 10
1 <= n <= 10
1 <= m <= 300
1 <= D[i] <=100
1 <= x[i] <=D[i]

Output Format

Output one line for each test case. Since the answer can be really huge, output it modulo 10^9 + 7.



Solution :



title-img


                            Solution in C :

In C++ :





/* Enter your code here. Read input from STDIN. Print output to STDOUT */
#include <iostream>
#include <memory.h>

const int maxn = 10;
const int maxm = 10000;
const long long modulo = 1000000007;

int D[maxn];
int X[maxn];

int n,m;
int solve(){
	std::cin>>n>>m;
	for (int i=0; i<n; i++)
		std::cin>>X[i];
	for (int i=0; i<n; i++)
		std::cin>>D[i];

	long long totalway[n][m+1];
	for (int i=0; i<n; i++){		
		long long total[D[i]];
		memset(total, 0, sizeof(total));
		total[X[i]-1] = 1;
		long long ans;
		totalway[i][0] = 1;
		for (int step=1; step<=m; step++){
			long long tmp[D[i]];
			for (int j=0; j<D[i]; j++){
				tmp[j] = 0;
				if (j>0) tmp[j] += total[j-1];
				if (j<D[i]-1) tmp[j] += total[j+1];
				tmp[j] %= modulo;
			}
			totalway[i][step] = 0;
			for (int j=0; j<D[i]; j++){
				total[j] = tmp[j];
				totalway[i][step] += total[j];
				totalway[i][step] %= modulo;
			}
        	}		
  	}	
	
	long long C[m+1][m+1];
	for (int i=0; i<=m; i++){
		C[i][0] = 1;
		for (int j=1; j<=i; j++)
			C[i][j] = (C[i-1][j]+C[i-1][j-1])%modulo;
		for (int j=i+1; j<=m; j++)
			C[i][j] = 0;
	}
		
	long long result[n][m+1];	
	for (int i=0; i<n; i++)
		for (int step=0; step<=m; step++){
			if (i==0){
				result[i][step] = totalway[i][step];
				continue;
			}
			result[i][step] = 0;
			for (int k=0; k<=step; k++){
				long long tmp = (result[i-1][k]*totalway[i][step-k])%modulo;
				tmp = tmp*C[step][step-k]%modulo;
				result[i][step] += tmp;
				result[i][step] %= modulo;
			}
			
		}
	std::cout<<result[n-1][m]<<std::endl;

}
int main(){
	int T;
	std::cin>>T;
	while (T>0){
		solve();
		T--;
	}
	return 0;
}








In Java :





import java.io.*;
import java.util.*;

public class Solution {
	
	public static final int MOD = 1000000007;
	public static final int MAXSTEPS = 310;
	
	public static void main(String[] args) throws IOException{
		long[][] pascals = new long[MAXSTEPS][];
		for (int i=0; i<MAXSTEPS; i++){
			pascals[i] = new long[i+1];
			pascals[i][0] = 1;
			for (int j=1; j<pascals[i].length; j++){
				pascals[i][j] = pascals[i-1][j-1];
				if (j<pascals[i-1].length)
					pascals[i][j] += pascals[i-1][j];
				pascals[i][j] %= MOD;
			}
		}
		
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	//BufferedReader in = new BufferedReader(new FileReader("test.in"));
	int cases = Integer.parseInt(in.readLine());
	for (int test = 0; test<cases; test++){
		StringTokenizer st = new StringTokenizer(in.readLine());
		int dims = Integer.parseInt(st.nextToken());
		int steps = Integer.parseInt(st.nextToken());
		int[] starts = new int[dims];
		st = new StringTokenizer(in.readLine());
		for (int i=0; i<dims; i++)
			starts[i] = Integer.parseInt(st.nextToken());
		int[] bounds = new int[dims];
		st = new StringTokenizer(in.readLine());
		for (int i=0; i<dims; i++)
			bounds[i] = Integer.parseInt(st.nextToken());
	
		long[] numWays = new long[steps+1];
		numWays[0] = 1;
		for (int i=0; i<dims; i++){
			long[] tempWays = new long[numWays.length];
			long[] nextDimWays = numPossSteps(starts[i], bounds[i], steps);

			for (int j=0; j<tempWays.length; j++){
				for (int k=0; k<=j; k++){
					long toAdd = (numWays[k]*nextDimWays[j-k])%MOD;
					toAdd *= pascals[j][k];
					tempWays[j] += toAdd%MOD;
					tempWays[j] %= MOD;
				}
			}
			numWays = tempWays;
		}
			
		System.out.println(numWays[steps]);
	}
}
	
	public static long[] numPossSteps(int start, int bound, int steps){
		long[] ret = new long[steps+1];
		ret[0] = 1;
		long[] trackLoc = new long[bound];
		trackLoc[start-1] = 1;
		for (int i=1; i<ret.length; i++){
			long[] nextTrack = new long[trackLoc.length];
			for (int j=0; j<trackLoc.length; j++){
				if (j>0)
					nextTrack[j] += trackLoc[j-1];
				if (j+1<bound)
					nextTrack[j] += trackLoc[j+1];
				nextTrack[j] %= MOD;
			}
			trackLoc = nextTrack;
			ret[i] = sum(trackLoc);
		}
		return ret;
	}
	
	public static long sum(long[] array){
		long sum = 0;
		for (int i=0; i<array.length; i++){
			sum+=array[i];
			sum %= MOD;
		}
		return sum;
	}
}








In C :





typedef long long int LL;
int mod=(int)(1e9+7);
int ways[302][102],fact[501],mi[501];
LL dp[12][302],tmp;
int x[12],d[12],i,j,k,t,n,m;
int res;
int raise(int pow,int power){
    res=1;
    while(power){
        if(power&1) res=((LL)res*pow)%mod;
        pow=((LL)pow*pow)%mod;
        power>>=1;
    }
    return res;
}
int modularInverse(int num){
    return raise(fact[num],mod-2);
}
int main(){
    fact[0]=1;
    for(i=1;i<=300;i+=1) fact[i]=((LL)fact[i-1]*i)%mod;
    mi[0]=1;
    for(i=1;i<=300;i+=1) mi[i]=modularInverse(i);
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i+=1) scanf("%d",&x[i]);
        for(i=1;i<=n;i+=1) scanf("%d",&d[i]);
        dp[0][0]=1;
        for(k=1;k<=n;k+=1){
            for(j=1;j<=d[k];j+=1) ways[0][j]=1;
            for(i=1;i<=m;i+=1){
                for(j=1;j<=d[k];j+=1){
                    ways[i][j]=0;
                    if(j>1)
                    ways[i][j]+=ways[i-1][j-1];
                    if(ways[i][j]>=mod) ways[i][j]-=mod;
                    if(j<d[k])
                    ways[i][j]+=ways[i-1][j+1];
                    if(ways[i][j]>=mod) ways[i][j]-=mod;
                }
            }
            for(i=0;i<=m;i+=1){
                dp[k][i]=0;
                for(j=0;j<=i;j+=1){
                    tmp=(dp[k-1][i-j]*ways[j][x[k]])%mod;
                    dp[k][i]=(dp[k][i]+(tmp*mi[j])%mod);
                    if(dp[k][i]>=mod) dp[k][i]%=mod;
                }
            }
        }
        printf("%lld\n",(dp[n][m]*fact[m])%mod);
    }
    return 0;
}








In Python3 :





T = int(input())
MOD = 1000000007

C = [[0] * 400 for _ in range(400)]

C[0][0] = 1
for i in range(400):
    C[i][0], C[i][i] = 1, 1
    for j in range(1, i):
        C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD

for t in range(T):
    N, M = [int(c) for c in input().split()]
    X = [int(c) for c in input().split()]
    D = [int(c) for c in input().split()]

    # dp[N][D[i]][M+1]
    dp = [[[0] * (M+1) for j in range(D[i])] for i in range(N)]

    for i in range(N):
        for j in range(D[i]):
            dp[i][j][0] = 1

            if j > 0:
                dp[i][j][1] += 1
            if j < D[i] - 1:
                dp[i][j][1] += 1

        for m in range(2, M+1):
            for j in range(D[i]):
                if j > 0:
                    dp[i][j][m] += dp[i][j-1][m-1]
                if j < D[i] - 1:
                    dp[i][j][m] += dp[i][j+1][m-1]

    total = [dp[0][X[0]-1][m] for m in range(M+1)]

    for i in range(1, N):
        for j in reversed(range(1, M + 1)):
            total[j] = sum(total[k] * C[j][k] * dp[i][X[i]-1][j-k] for k in range(j+1)) 

    print(total[M] % MOD)
                        








View More Similar Problems

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →