[Python] How the recursion in python works while finding the longest increasing sequence?

Discussão em 'Python' iniciado por Stack, Agosto 24, 2025.

  1. Stack

    Stack Membro Participativo

    def longest_increasing_path(matrix):
    if not matrix:
    return 0

    rows, cols = len(matrix), len(matrix[0])
    cache = [[0] * cols for _ in range(rows)]

    def dfs(i, j):
    if cache[j]:
    return cache[j]

    val = matrix[j]
    paths = 0

    for ni, nj in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
    if 0 <= ni < rows and 0 <= nj < cols and matrix[ni][nj] > val:
    paths = max(paths, dfs(ni, nj))

    cache[j] = paths + 1
    return cache[j]

    return max(dfs(i, j) for i in range(rows) for j in range(cols))


    I have this code for finding the longest increasing path in 2D matrix with numbers. I don't understand how the hell is working paths = max(paths, dfs(ni, nj)) in function. Especially, I dont understand from where the function gets the length if it have only the "Path" equals to 0. Please, explain me how recursion works in this case, i`m kinda newbie in this theme

    Continue reading...

Compartilhe esta Página