zoukankan      html  css  js  c++  java
  • 【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)
  • 相关阅读:
    正则表达式点滴
    异步处理与界面交互
    关于利用VS2008创建项目遇到的小困惑备忘
    using App.cofig to Store value
    Castle ActiveRecord学习笔记三:初始化配置
    无服务器端的UDP群聊功能剖析
    为VS2010默认模板添加版权信息
    理论有何用?不问“何用”,先问“用否”!
    微软没有公开的游标分页
    那些满脑子只考虑后台数据库的人他整天研究的就是针对自己查询一些数据的sql语句
  • 原文地址:https://www.cnblogs.com/seyjs/p/10026173.html
Copyright © 2011-2022 走看看