Grid Walking (Score 50 points):
You are situated in an N dimensional grid at position (x_1,x2,...,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. (So there are always 2N
possible different moves). In how many ways can you take M
steps such that you do not leave the grid at any point? You leave the grid if you for any x_i
, either x_i <= 0 or x_i > D_i
.
Input:
The first line contains the number of test cases T
. T
test cases follow. For each test case, the first line contains N
and M
, the second line contains x_1,x_2...,x_N
and the 3rd line contains D_1,D_2,...,D_N
.
So, in the above solution I'm trying to take one dimensional array.
The website claims 38753340
to be the answer, but I'm not getting it.
public class GridWalking {
/**
* @param args
*/
public static void main(String[] args) {
try {
long arr[] = new long[78];
long pos = 44;
long totake = 287;
/*
* Double arr[] = new Double[3]; Double pos = 0; Double totake = 5;
*/
Double val = calculate(arr, pos, totake);
System.out.println(val % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
public static HashMap<String, Double> calculated = new HashMap<String, Double>();
private static Double calculate(long[] arr, long pos, long totake) {
if (calculated.containsKey(pos + "" + totake)) {
return calculated.get(pos + "" + totake);
}
if (0 == totake) {
calculated.put(pos + "" + totake, new Double(1));
return new Double(1);
}
if (pos == arr.length - 1) {
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
if (pos == 0) {
Double b = calculate(arr, pos + 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
Double a = calculate(arr, pos + 1, totake - 1);
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = (a + b);
calculated.put(pos + "" + totake, ret);
return ret;
}
}