This one was really fun!
Here's the problem description.
My approach involved the following ideas:
- We can precalculate the number of ways to stay within a one dimensional segment of a particular length, starting at a particular place, and using a particular number of moves.
- From here, the number of ways to stay within D dimensions of the grid using M moves can be found by going through all possible ways of splitting M into two chunks (say, k and M-k) and interleaving the k moves we use to stay within dimension D (at starting position x_D) with the number of ways to stay within D-1 dimensions using M-k moves.
Of course, there is a trick in counting the number of ways to interleave the moves to stay within 1 dimension with the number of ways to interleave the moves to stay within the remaining D-1 dimensions. ;)
Say for every move in dimension D, we write a 0. For every move in the remaining D-1 dimensions, we write a 1. The number of interleavings is, of course, the same as the number of possible binary strings composed in this fashion. If we have M total moves, k of which are made in dimension D, this gives, of course, M choose k possible interleavings.
But we have to give the output modulo 10^9 + 7! How do we calculate M choose k modulo this number? Fortunately p = 1E9 + 7 is prime, so the group of integers modulo p gives a field. This means that we can simply calculate M choose k (mod p) as M! * (k!)^-1 * ((M-k)!)^-1, all modulo p, of course. Since p is prime we are guaranteed that the numbers k! and (M-k)! have multiplicative inverses. I used the extended Euclidean algorithm to get these, although I believe you could just as well raise them to the p-2 power (which, by Fermat's theorem, gives the multiplicative inverse).
Whew! It's great to see a problem that combines concepts from dynamic programming, discrete math, and number theory!