Longest Path in 2D Array

Given a 2D array of integers, this problem looks for the longest path from the top left to the bottom right where each step only visits cells with values greater than or equal to the current cell.

Problem

Given a 2D array of integers, find the length of the longest path from the top left to the bottom right that only visits cells with values greater than or equal to the current cell.

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by TechCoders
# Solution:
# The solution is to use dynamic programming.
# The idea is to create a 2D array of the same size as the input array.
# The value of each cell in the 2D array is the length of the longest path from the top left to that cell.
# The value of the top left cell is 1.
# The value of the other cells is the maximum of the value of the cell above and the value of the cell to the left, plus 1.
# The value of the bottom right cell is the length of the longest path.
# The time complexity is O(n^2) and the space complexity is O(n^2).

def longest_path(arr):
    n = len(arr)
    dp = [[0 for _ in range(n)] for _ in range(n)]
    dp[0][0] = 1
    for i in range(1, n):
        if arr[i][0] >= arr[i - 1][0]:
            dp[i][0] = dp[i - 1][0] + 1
        else:
            dp[i ][0] = 1
    for j in range(1, n):
        if arr[0][j] >= arr[0][j - 1]:
            dp[0][j] = dp[0][j - 1] + 1
        else:
            dp[0][j] = 1
    for i in range(1, n):
        for j in range(1, n):
            if arr[i][j] >= arr[i - 1][j] and arr[i][j] >= arr[i][j - 1]:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + 1
            elif arr[i][j] >= arr[i - 1][j]:
                dp[i][j] = dp[i - 1][j] + 1
            elif arr[i][j] >= arr[i][j - 1]:
                dp[i][j] = dp[i][j - 1] + 1
            else:
                dp[i][j] = 1
    return dp[n - 1][n - 1]

arr = [[1, 2, 9], [5, 3, 8], [4, 6, 7]]
print(longest_path(arr))

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to use dynamic programming. The idea is to create a 2D array of the same size as the input array. The value of each cell in the 2D array is the length of the longest path from the top left to that cell. The value of the top left cell is 1. The value of the other cells is the maximum of the value of the cell above and the value of the cell to the left, plus 1. The value of the bottom right cell is the length of the longest path. The time complexity is O(n^2) and the space complexity is O(n^2).

Evaluated at: 2022-10-11 01:04:57