(补)算法刷题Day24: BM61 矩阵最长递增路径

题目链接

思路

方法一:dfs暴力回溯

使用原始used数组+4个方向遍历框架 =, 全局添加一个最大值判断最大的路径长度。

方法二:加上dp数组记忆的优雅回溯

抛弃掉used数组,使用dp数组来记忆遍历过的节点的最长递增路径长度。每遍历到已经记录过的坐标,就直接返回即可。

方法一代码

python 复制代码
import copy
max_result_len = -1
result = []
direct = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(matrix, used, row_n, col_m, x, y, path):
    # 判断是否合法
    global max_result_len
    global result
    if len(path) > max_result_len:
        max_result_len = len(path)
        print(max_result_len)
        print(path)
        result = copy.deepcopy(path)
    if x < 0 or y < 0 or x >= row_n or y >= col_m:
        return
    if used[x][y]:
        return
    # 如果当前节点值是小于前一个,则pass
    if matrix[x][y] <= path[-1]:
        return
    used[x][y] = True
    path.append(matrix[x][y])
    for dx, dy in direct:
        nx = x + dx
        ny = y + dy
        dfs(matrix, used, row_n, col_m, nx, ny, path)
    used[x][y] = False
    path.pop()
class Solution:
    def solve(self, matrix: List[List[int]]) -> int:
        # write code here
        row = len(matrix)
        col = len(matrix[0])
        used = [[False for _ in range(row)] for _ in range(col)]
        for i in range (row):
            for j in range (col):
                dfs(matrix, used, row, col, i, j, [-1])
        return max_result_len-1

方法二代码

python 复制代码
direct = [(-1, 0), (1, 0), (0, -1), (0, 1)]

def dfs(matrix, row_n, col_m, x, y, path,dp):
    # 判断是否合法
    if x < 0 or y < 0 or x >= row_n or y >= col_m:
        return 0
    # 如果当前节点值是小于前一个,则pass
    if matrix[x][y] <= path[-1]:
        return 0
    # 如果 dp 记录过就直接加上
    if dp[x][y] != -1:
        return dp[x][y]
    path.append(matrix[x][y])
    my_max = -1
    for dx, dy in direct:
        nx = x + dx
        ny = y + dy
        sub_max = dfs(matrix, row_n, col_m, nx, ny, path,dp)
        my_max = max(sub_max,my_max)
    path.pop()
    dp[x][y] = my_max+1
    return my_max+1
class Solution:
    def solve(self, matrix: List[List[int]]) -> int:
        row = len(matrix)
        col = len(matrix[0])
        dp = [[-1 for _ in range(row)]for _ in range(col)]
        max_result_len = -1
        for i in range(row):
            for j in range(col):
                m = dfs(matrix,row, col, i, j, [-1],dp)
                max_result_len = max(max_result_len, m)
        return max_result_len

这道题的dp卡了我很久。让我好几天都没有刷题的欲望。在需要机械化完成的任务面前,情绪更多时候真的是没用的东西。反正都要做的,早做晚做都是要做,开心也要做不开心也要做,倒不如不怀情绪地认真做。别急~

相关推荐
Norvyn_75 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
chao_78923 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
呆呆的小鳄鱼34 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香34 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely35 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071235 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_1 小时前
cf1925B&C
数据结构·算法
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥1 小时前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json