Out of Boundary Paths
There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.
class Solution {
private:
static const int MOD_NUM = 1e9 + 7;
public:
int findPaths(int m, int n, int N, int i, int j) {
/*
0 1 2 3 4 5 6 7
0@ @ @ @ @ @ @ @
1@ O O O O O O @
2@ O O O O O O @
3@ O O O O O O @
4@ O O O O O O @
5@ @ @ @ @ @ @ @
*/
vector<vector<vector<int> > > num(m + 2, vector<vector<int>>(n + 2, vector<int>(N + 1, -1)));
for (int k = 1; k <= N; ++k) {
this->findPathsInner(m, n, k, i + 1, j + 1, num);
}
int ret = 0;
for (int k = 1; k <= N; ++k) {
if (num[i + 1][j + 1][k] > 0) {
//cout<<k<<"\t"<<num[i + 1][j + 1][k]<<endl;
ret = (num[i + 1][j + 1][k] % MOD_NUM + ret % MOD_NUM) % MOD_NUM;
}
}
return ret;
}
void findPathsInner(int m, int n, int N, int i, int j, vector<vector<vector<int> > >& num) {
if (i <= 0 || j <= 0 || i > m || j > n) {
if (N == 0) {
num[i][j][N] = 1;
} else {
num[i][j][N] = 0;
}
return ;
}
//已经求出来了
if (num[i][j][N]>=0) {
return;
}
//没有到边界,已经走完了N步
if (N == 0) {
num[i][j][N] = 0;
return;
}
//搜索
this->findPathsInner(m, n, N - 1, i - 1, j, num);
this->findPathsInner(m, n, N - 1, i, j - 1, num);
this->findPathsInner(m, n, N - 1, i + 1, j, num);
this->findPathsInner(m, n, N - 1, i, j + 1, num);
num[i][j][N] = ((( num[i - 1][j][N - 1] % MOD_NUM
+ num[i + 1][j][N - 1] % MOD_NUM) % MOD_NUM
+ num[i][j - 1][N - 1] % MOD_NUM) % MOD_NUM
+ num[i][j + 1][N - 1] % MOD_NUM) % MOD_NUM;
return ;
}
};