• 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步可以走出的路径个数之和,知道了这个之后,我们就可以以这个公式作为状态转移方程。

  • 相关阅读:
    redis 1 简单介绍和存储的数据结构
    mysql 14 覆盖索引+回表
    mysql 13 B+tree中存储数据的格式 页
    java Arrays.asList() 数组转集合
    java 迭代器
    mysql 12 SQL优化策略
    mysql 11 执行计划
    mysql 10 索引面试题分享
    搭建一个开源项目2-打造另一个环境以及解决上期问题
    搭建一个开源项目1-如何搭建Linux虚拟机
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9756864.html
Copyright © 2020-2023  润新知