576 Out of Boundary Paths
1. Question
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:
Example 2:
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].
2. Implementation
(1) DP
思想: 这道题要我们求出从(i, j)出发,有多少种路径可以让我们把球移除边界. 利用动态规划的思想,dp[i][j][k]表示从(i,j)出发,走k步可以走出边界的路径总数,显然dp[i][j][k]的状态取决于它四周(上下左右)的状态影响,
即dp[i][j][k] = dp[i - 1][j][k - 1] + dp[i + 1][j][k - 1] + dp[i][j - 1][k - 1] + dp[i][j + 1][k - 1], base case为当(i,j)在边界位置时, dp[i][j][k] = 1,因为在边界上只需要1步可以走出边界
3. Time & Space Complexity
DP: 时间复杂度O(m * n * N), 空间复杂度O(m * n * N)
Last updated
Was this helpful?