题目如下:
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].
解题思路:这种题目还是用动态规划吧。记dp[i][j][k] = v 表示从起点开始移动i步到达(j,k)点一共有v种走法,因为每个节都可以从上下左右四个方向移动一步到达该点,很显然有 dp[i][j][k] = dp[i-1][j-1][k] + dp[i-1][j+1][k] + dp[i-1][j][k-1] + dp[i-1][j][k+1] 。最后再累加出所有位于边界的点的走法,假设边界的点的坐标是(x,y),依次判断x == 0, x == m - 1 , y == 0 ,y == n-1四个条件,从这个点走到边界外的走法 = 到达这个点的走法 * 满足条件的个数。
代码如下:
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ if N == 0: return 0 dp = [] for v in range(N): tl = [] for v in range(m): tl.append([0] * n) dp.append(tl) dp[0][i][j] = 1 for x in range(1,len(dp)): for y in range(len(dp[x])): for z in range(len(dp[x][y])): direction = [(0, 1), (0, -1), (-1, 0), (1, 0)] for (ny, nz) in direction: if (y + ny) >= 0 and (y + ny) < m and (z + nz) >= 0 and (z + nz) < n: dp[x][y][z] += dp[x - 1][y + ny][z + nz] res = 0 for x in range(len(dp)): for y in range(len(dp[x])): for z in range(len(dp[x][y])): if y == 0: res += dp[x][y][z] if z == 0: res += dp[x][y][z] if y == m - 1: res += dp[x][y][z] if z == n - 1: res += dp[x][y][z] #print dp return res % (pow(10,9)+7)