zoukankan      html  css  js  c++  java
  • 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]]))
  • 相关阅读:
    字典常用操作复习
    列表常用方法复习
    爬虫流程复习
    协程解决素数
    yield 复习
    多线程复习2
    多线程复习1
    异常 巩固3
    logging日志基础示例
    2019最新百度网盘不限速下载教程
  • 原文地址:https://www.cnblogs.com/cong12586/p/14343922.html
Copyright © 2011-2022 走看看