• 1631.最小体力消耗路径


    from typing import List
    class Solution:
    # 自己写的深搜,没办法通过,超时。
    def minimumEffortPath1(self, heights: List[List[int]]) -> int:
    # 判断列表是否为空
    if len(heights) == 0 or len(heights[0]) == 0:
    return 0
    row,col = len(heights),len(heights[0])
    # 定义一个标志位列表。
    dp = [[float('inf')] * col for _ in range(row)]
    # 设置最小体力变量。
    self.min_num = float('inf')
    dp[0][0] = 0
    # 进行深搜。
    self.dfs(0,0,heights,0,dp,row,col)
    return self.min_num
    def dfs(self,cur_row,cur_col,heights,consume,dp,row,col):
    if cur_row == row - 1 and cur_col == col - 1 and consume < self.min_num:
    self.min_num = consume
    moves = [[-1,0],[0,-1],[1,0],[0,1]] #四种不同的方向左上右下
    for i,j in moves:
    cur_row_now,cur_col_now = cur_row + i,cur_col + j
    if 0 <= cur_row_now < row and 0 <= cur_col_now < col:
    consume = max(abs(heights[cur_row_now][cur_col_now] - heights[cur_row][cur_col]),dp[cur_row][cur_col])
    if consume < dp[cur_row_now][cur_col_now]:
    dp[cur_row_now][cur_col_now] = consume
    self.dfs(cur_row_now,cur_col_now,heights,consume,dp,row,col)
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
    # 行和列的值。
    row,col = len(heights),len(heights[0])
    # 行和列小于等于1,直接返回。
    if row <= 1 and col <= 1 :return 0
    dp = [[float('inf')] * col for _ in range(row)]
    dp[0][0] = 0
    moves = [[-1,0],[0,-1],[1,0],[0,1]] #四种不同的方向左上右下
    res = float('inf') # 定义res变量存储最后的变量
    queue = [[0,0]] # 表示当前位置。
    # 队列为空代表全部广搜完成。
    while queue:
    # 取出一个点。
    start_row,start_col = queue.pop(0)
    # 上下左右开始进行运行。
    for i,j in moves:
    cur_row,cur_col = start_row + i,start_col + j
    # 判断是否出界。
    if 0 <= cur_row < row and 0 <= cur_col < col:
    # 求出当前体力值应该是少。
    consume = max(abs(heights[cur_row][cur_col] - heights[start_row][start_col]),dp[start_row][start_col])
    if cur_row == row - 1 and cur_col == col - 1 and consume < res:
    res = consume
    # 注意这里如果现在的体力值就已经比当前节点的体力值大了,那么就没有必要接着走了。
    elif consume < dp[cur_row][cur_col]:
    dp[cur_row][cur_col] = consume
    queue.append([cur_row,cur_col])
    return res
    A = Solution()
    print(A.minimumEffortPath1([[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]))
  • 相关阅读:
    [转载]Install Opera 12.16 Web Browser in CentOS/RHEL and Fedora
    [转载]CentOS 6.5 安装五笔输入法
    [转载]Lenovo E431 装Centos7无线驱动安装
    ElasticSearch的按日期排序问题
    [转载]java自带线程池和队列详细讲解
    [转载]Redis后台启动
    [转载]Process工具类,提供设置timeout功能
    [转载]使用java.lang.Process类的简单例子
    [转载]SecureCRT 绝佳配色方案, 保护你的眼睛
    4.二叉搜索树转为有序双向链表(递归算法与非递归算法)
  • 原文地址:https://www.cnblogs.com/cong12586/p/14343922.html
Copyright © 2020-2023  润新知