【leetcode】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].

解题思路:这种题目还是用动态规划吧。记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)

 

转载于:https://www.cnblogs.com/seyjs/p/10026173.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值