• 980不同路径III


    题目: 在二维网格 grid 上,有 4 种类型的方格:
        1 表示起始方格。且只有一个起始方格。
        2 表示结束方格,且只有一个结束方格。
        0 表示我们可以走过的空方格。
        -1 表示我们无法跨越的障碍。
    返回在四个方向(上、下、左、右)上行走时,从起始方格到结束方格的不同路径的数目,每一个无障碍方格都要通过一次。

    来源: https://leetcode-cn.com/problems/unique-paths-iii/

    法一: 自己的代码

    思路: 基本的回溯算法,注意for循环时变量要赋给temp,不要赋给coor,回溯函数传递变量的时候很容易出错!

    # 执行用时 :72 ms, 在所有 python3 提交中击败了52.94% 的用户
    # 内存消耗 :12.8 MB, 在所有 python3 提交中击败了100.00%的用户
    from typing import List
    class Solution:
        def uniquePathsIII(self, grid: List[List[int]]) -> int:
            r = len(grid)
            c = len(grid[0])
            coordinate = []
            bar = []
            ans = [0]
            # 记录可以走的格子的坐标,起始点,终止点
            for i in range(r):
                for j in range(c):
                    if grid[i][j] in [0]:
                        coordinate.append((i,j))
                    elif grid[i][j] == 1:
                        start = (i,j)
                    elif grid[i][j] == 2:
                        end = (i,j)
                    else:
                        bar.append((i,j))
            coordinate.append(end)
            dire = [[0,1],[1,0],[0,-1],[-1,0]]
            def recursion(coor):
                # 如果当前格子为终点,则只有两种情况,一种是找到一条路径了,另一种是半中间走到终点了,必定是不满足条件的路径,直接返回
                if coor == end:
                    if len(coordinate) == 0:
                        ans[0] += 1
                    return
                for p,q in dire:
                    # 特别要注意这里要赋值给temp,不能是coor,如果是coor的话,第二次for循环的时候是直接在第一次for循环的基础上修改值的,
                    temp = (coor[0]+p, coor[1]+q)
                    # 如果出界了,或者走到有障碍的格子了或者之前已经走过了,continue
                    if (-1 < temp[0] < r) + (-1 < temp[1] < c) != 2 or temp in bar or temp not in coordinate:
                        continue
                    coordinate.remove(temp)
                    recursion(coor=temp)
                    coordinate.append(temp)
            recursion(start)
            return ans[0]
    if __name__ == '__main__':
        duixiang = Solution()
        a = duixiang.uniquePathsIII([[1,0,0,0],[0,0,0,0],[0,0,0,2]])
        print(a)
    View Code

    ttt

  • 相关阅读:
    java简单计算器,只能鼠标点击数字
    可以掉落和滑动的星星
    servlet生成数字验证码
    web服务器底层-http请求与相应
    Codeforces 990D Graph And Its Complement 【构造】【性质】
    2018美团CodeM编程大赛 Round A Problem 2 下棋 【贪心】
    Codeforces 988F Rain and Umbrellas 【dp】
    Codeforces 988D Points and Powers of Two 【性质】【卡常】
    Codeforces 981D Bookshelves 【dp】【性质】
    POJ 2104 K-th Number 【主席树】【不带修改】
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12133505.html
Copyright © 2020-2023  润新知