在矩阵中寻找最长连续路径

-1 投票
0 回答
34 浏览
提问于 2025-04-12 08:54

我受到了Leetcode第329题的启发,题目是“矩阵中的最长递增路径”。不过,我想做的不是找递增路径,而是找最长的连续路径,这条路径的相邻单元格(上下左右)之间的值差必须是±1,也就是说,当前单元格的值和相邻单元格的值只能相差1。例如:

[[3,4,5],
[4,3,4],
[2,2,1]] should return [4, 3, 4, 5, 4, 3, 2, 1].

我想到了下面的代码,我可以用abs()函数来处理这个问题,但这样做让我遇到了一个错误:RecursionError: maximum recursion depth exceeded while calling a Python object。有人能告诉我为什么会出现递归错误吗?我该如何改进我的代码呢?

def longestConsecutiveTrail(matrix):
    def dfs(i, j):
        # Check if the result for this cell is already computed
        if not dp[i][j]:
            val = matrix[i][j]
            # For each of the four directions, check if the value is either one less or one more than the current cell
            # Update the dp table with 1 (for the current cell) + max value from all possible directions
            dp[i][j] = 1 + max(
                dfs(i - 1, j) if i and abs(val - matrix[i - 1][j]) == 1 else 0,
                dfs(i + 1, j) if i < M - 1 and abs(val - matrix[i + 1][j]) == 1 else 0,
                dfs(i, j - 1) if j and abs(val - matrix[i][j - 1]) == 1 else 0,
                dfs(i, j + 1) if j < N - 1 and abs(val - matrix[i][j + 1]) == 1 else 0)
        return dp[i][j]

    if not matrix or not matrix[0]:
        return 0

    M, N = len(matrix), len(matrix[0])
    dp = [[0] * N for _ in range(M)]  # DP table to store the length of the longest trail from each cell

    # Iterate over every cell in the matrix, calling dfs for each one to find the longest consecutive trail
    return max(dfs(x, y) for x in range(M) for y in range(N))

0 个回答

暂无回答

撰写回答