题目:
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].
思路:
将问题反过来想则思路会更简单:假设在格子的边界外面有无限多个球,时间每过一个单元,都会从每个边界格子外面移动进来一个球。那么问题就转换为:经过N步之后,在(i, j)处将会聚集多少个球。所以我们可以定义dp[x][mi][ni]表示在第x步的时候,格子(mi, ni)处会有多少个球,则最终只需要返回dp[N][i][j]即可。具体可以见下面的代码片段1。其时间复杂度是O(mnN),空间复杂度也是O(mnN)。
通过观察下面代码中的状态转移方程可以看出,dp[x][mi][ni]只和dp[x - 1][mi +- 1][ni +- 1]四个状态有关,所以我们就不需要记录N个状态了,只需要记录当前步和上一步的状态即可,因为可以采用循环移动的方法来不断进行状态转移。这样空间复杂度可以进一步降低到O(mn)。
代码:
1、O(mnN)空间复杂度:
class Solution {
public:
int findPaths(int m, int n, int N, int i, int j) {
unsigned int dp[51][50][50] = {};
for (int x = 1; x <= N; ++x) {
for (int mi = 0; mi < m; ++mi) {
for (int ni = 0; ni < n; ++ni) {
dp[x][mi][ni] = ((mi == 0 ? 1 : dp[x - 1][mi - 1][ni]) + // from up to here
(mi == m - 1? 1 : dp[x - 1][mi + 1][ni]) + // from down to here
(ni == 0 ? 1 : dp[x - 1][mi][ni - 1]) + // from left to here
(ni == n - 1 ? 1 : dp[x - 1][mi][ni + 1]) // from right to here
) % 1000000007;
}
}
}
return dp[N][i][j];
}
};
2、O(mn)空间复杂度:
class Solution {
public:
int findPaths(int m, int n, int N, int i, int j) {
unsigned int dp[2][50][50] = {};
for (int x = 1; x <= N; ++x) {
for (int mi = 0; mi < m; ++mi) {
for (int ni = 0, nc = x % 2, np = (x - 1) % 2; ni < n; ++ni) {
dp[nc][mi][ni] = ((mi == 0 ? 1 : dp[np][mi - 1][ni]) +
(mi == m - 1 ? 1 : dp[np][mi + 1][ni]) +
(ni == 0 ? 1 : dp[np][mi][ni - 1]) +
(ni == n - 1 ? 1 : dp[np][mi][ni + 1])
) % 1000000007;
}
}
}
return N % 2 == 0 ? dp[0][i][j] : dp[1][i][j];
}
};