Finding the Longest Consecutive Path in a Matrix

36 Views Asked by At

I was inspired by the Leetcode #329. Longest Increasing Path in a Matrix. However instead of finding the increasing path, I'd like to find the longest consecutive path in which exploring adjacent cells (up, down, left, right) that have a value difference of ±1 from the current cell's value. For example:

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

I figured with the code below, I can use the abs() but doing so made my code get this error: RecursionError: maximum recursion depth exceeded while calling a Python object. Can you someone tell me why it's having a recursion error and how can I improve it?

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

There are 0 best solutions below