576. 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.
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:
1. Once you move the ball out of boundary, you cannot move it back.
2. The length and height of the grid is in range [1,50].
3. N is in range [0,50].
Approach
- 题目大意是一个球移动不多于N次,能走出边界的有多少种走法,很明显是要用动态规划处理,否则超时,这里我采用记忆化搜索,动态规划的另一种写法,这道题其实也不难,我用一个三维数组
res[N][i][j]
记忆表示当这个球已移动N
次,在坐标为i
和j
的状态下有多少种走法,现在我们来讨论一下该怎么搜索,因为没有障碍,所以我们要搜索球移动上下左右,然后边界很明显就是当i
和j
到达矩阵的边界,还有就是已经移动了N次。 - 多练多想多看,就容易有思路,多看不同的写法,有时是可以猜状态转移方程的。
Code
class Solution {
public:
int mod = 1000000007;
int findPaths(int m, int n, int N, int i, int j) {
vector<vector<vector<int>>>res(N+1, vector<vector<int>>(m, vector<int>(n, -1)));
return DFS(res,m, n, N, i, j);
}
int DFS(vector<vector<vector<int>>> &res, int m, int n, int N, int i, int j) {
if (i<0 || j<0 || i >= m || j >= n) {
return 1;
}
if (N <= 0)return 0;
if (res[N][i][j] != -1)return res[N][i][j]%mod;
res[N][i][j] = (((DFS(res, m, n, N - 1, i + 1, j)%mod + DFS(res, m, n, N - 1, i, j + 1))%mod + DFS(res, m, n, N - 1, i - 1, j))%mod + DFS(res, m, n, N - 1, i, j - 1))%mod;
return res[N][i][j]%mod;
}
};