Question:
What is the Longest Increasing Path in a Matrix?

To find the longest increasing path in the matrix, you must traverse the matrix while adhering to a specific condition. It means that each cell in the path must have a value larger than the previous cell. The following is the way to solve this problem by using dynamic programming:


  • Initializing a memoization matrix: You can create a matrix to store each cell's lengths of longest-increasing paths. 

  • Define a recursive function: This function helps you explore each cell’s possible;e paths while keeping track of the maximum length.

  • Use memoization to avoid redundant calculations: Whenever you explore a cell, if you've already computed its longest increasing path length, use the memoization matrix to avoid redundant calculations.


The following is the code snippet of Python of the above approach:


def longestIncreasingPath(matrix):

    if not matrix:

        return 0


    rows, cols = len(matrix), len(matrix[0])

    memo = [[0] * cols for _ in range(rows)]


    def dfs(row, col):

        if memo[row][col]:

            return memo[row][col]


        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

        max_length = 1


        for dr, dc in directions:

            new_row, new_col = row + dr, col + dc

            if 0 <= new_row < rows and 0 <= new_col < cols and matrix[new_row][new_col] > matrix[row][col]:

                length = 1 + dfs(new_row, new_col)

                max_length = max(max_length, length)


        memo[row][col] = max_length

        return max_length


    longest_path = 0

    for i in range(rows):

        for j in range(cols):

            longest_path = max(longest_path, dfs(i, j))


    return longest_path


# Example usage:

matrix = [

    [9, 9, 4],

    [6, 6, 8],

    [2, 1, 1]

]

print(longestIncreasingPath(matrix))  # Output should be 4


Suggested blogs:

>>Why Typescript does not allow a union type in an array?

>>Fix: Strange compilation error with Typescript and Angular

>>What if the property 'X' does not exist on type 'FastifyContext<unknown>'?

>>How to get the type of a class property's getter/setter in TypeScript?

>>How to assign multiple const variables in a single declaration in TypeScript?

>>How to handle more than 100 cases neatly on Typescript?

>>Type inference with 'as const' IN TypeScript

>>Typescript Return argument: Tuple type or passed to rest parameter warning?

>>How can you read a Blob in Deno in TypeScript?

>>How to do Yup validation in form with TypeScript?


Submit
0 Answers