576.Out of Boundary Paths(一个三维数组的dp)

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:

avatar

Example 2:

Input:m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:

avatar

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].

Solution1:(TLE)

class Solution:
    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 i==-1 or j==-1 or i==m or j==n:
            return 1
        if N==0:
            return 0
        return self.findPaths(m,n,N-1,i-1,j) + self.findPaths(m,n,N-1,i+1,j) + self.findPaths(m,n,N-1,i,j+1) + self.findPaths(m,n,N-1,i,j-1)

Solution2:

class Solution:
    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
        MOD = 1000000000 + 7
        res = 0
        dp = [[[0 for p in range(N+1)]for q in range(n) ]for t in range(m)]
        for t in range(1,N+1):
            for p in range(m):
                for q in range(n):
                    left = 1 if p==0 else dp[p-1][q][t-1]
                    right = 1 if p==m-1 else dp[p+1][q][t-1]
                    up = 1 if q==0 else dp[p][q-1][t-1]
                    down = 1 if q==n-1 else dp[p][q+1][t-1]
                    dp[p][q][t] = (left + right + up + down)%MOD
        return dp[i][j][N]

对于一个起始点为i,j,N步可以走出的点的路径个数,等于该点周围的4个点,N-1步可以走出的路径个数之和,知道了这个之后,我们就可以以这个公式作为状态转移方程。

转载于:https://www.cnblogs.com/bernieloveslife/p/9756864.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值