There is an m x n
grid with a ball. The ball is initially at the position [startRow, startColumn]
. You are allowed to move the ball to one of the four adjacent four cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove
moves to the ball.
Given the five integers m
, n
, maxMove
, startRow
, startColumn
, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7
.
Example 1:
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6
Example 2:
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
Constraints:
1 <= m, n <= 50
0 <= maxMove <= 50
0 <= startRow <= m
0 <= startColumn <= n
题目链接:https://leetcode.com/problems/out-of-boundary-paths/
题目大意:求球通过maxMove步被移出区域的方案数
题目分析:很容易想到记忆化搜索,dp[i][j][k]表示到点(i, j)还剩k步时将球移除的方案数,于是上下左右记忆化搜索就好,然后会得到一个TLE,这里有一个关键且不难想的剪枝,当还剩k步,但此时球到四个边界的距离均大于等于k时其必不可能被移出去,返回0即可
2ms,时间击败100%
class Solution {
public int MOD = 1000000007;
public int dfs(int[][][] dp, int x, int y, int N, int m, int n) {
if (x >= m || y >= n || x < 0 || y < 0) {
return 1;
}
if (x >= N && y >= N && m - x > N && n - y > N) {
return 0;
}
if (dp[x][y][N] != 0) {
return dp[x][y][N];
}
if (N > 0) {
dp[x][y][N] = (dp[x][y][N] + dfs(dp, x - 1, y, N - 1, m, n)) % MOD;
dp[x][y][N] = (dp[x][y][N] + dfs(dp, x + 1, y, N - 1, m, n)) % MOD;
dp[x][y][N] = (dp[x][y][N] + dfs(dp, x, y - 1, N - 1, m, n)) % MOD;
dp[x][y][N] = (dp[x][y][N] + dfs(dp, x, y + 1, N - 1, m, n)) % MOD;
}
return dp[x][y][N];
}
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int[][][] dp = new int[m][n][maxMove + 1];
dfs(dp, startRow, startColumn, maxMove, m, n);
return dp[startRow][startColumn][maxMove] % MOD;
}
}