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.
Example 1:
Input:m = 2, n = 2, N = 2, i = 0, j = 0 Output: 6 Explanation:![]()
Example 2:
Input:m = 1, n = 3, N = 3, i = 0, j = 1 Output: 12 Explanation:![]()
Note:
- Once you move the ball out of boundary, you cannot move it back.
- The length and height of the grid is in range [1,50].
- N is in range [0,50].
我的思路:
1、写出递归方法,比较容易想 TLE
class Solution {
public:
int findPaths(int m, int n, int N, int i, int j) {
if(N>=0&&(i==-1||j==-1||i==m||j==n))
return 1;
else if(N==0) return 0;
int sum=0;
sum+=findPaths(m,n,N-1,i-1,j)+findPaths(m,n,N-1,i+1,j)+findPaths(m,n,N-1,i,j-1)+findPaths(m,n,N-1,i,j+1);
return sum%(1000000007);
}
};
2、改成存储版本得动态规划
递归函数的变量有N,i,j三个。将计算过得都存储起来.
class Solution {
public:
int findPaths(int m, int n, int N, int i, int j) {
vector<vector<vector<int>>> dp(N+1,vector<vector<int>>(m,vector<int>(n,-1)));//建立初始化动态规划数组全部是-1.因为0代表没有解决方案
return find(m,n,N,i,j,dp);
}
int find(int m, int n, int N, int i, int j,vector<vector<vector<int>>>& dp)
{
if(i==-1||j==-1||i==m||j==n)
{
return 1;
}
if(N==0)
return 0;
if(dp[N][i][j]>=0) return dp[N][i][j];//需要在后面判断,因为可能是越界的
dp[N][i][j]=(((find(m,n,N-1,i-1,j,dp)+find(m,n,N-1,i+1,j,dp))%M+find(m,n,N-1,i,j-1,dp))%M+find(m,n,N-1,i,j+1,dp))%M;//这种取模的情况要把所有的加和后面都取模
return dp[N][i][j];
}
int M=1000000007;
};
3、递归版本