Maximum number of elements in the path of a matrix

只愿长相守 提交于 2019-12-04 22:08:19

Try this recursion: The longest path starting at element (x, y) is the longest longest path starting at any of its strictly smaller neighbors, plus 1.

def longest_path(matrix):
    def inner_longest_path(x, y):
        best, best_path = 0, []
        # for all possible neighbor cells...
        for dx, dy in ((+1, 0), (-1, 0), (0, +1), (0, -1)):
            # if cell is valid and strictly smaller...
            if (0 <= x + dx < len(matrix) and 0 <= y + dy < len(matrix[x]) 
                    and matrix[x+dx][y+dy] < matrix[x][y]):
                n, path = inner_longest_path(x+dx, y+dy)
                # check if the path starting at that cell is better
                if n > best:
                    best, best_path = n, path
        return best + 1, [matrix[x][y]] + best_path

    return max(inner_longest_path(x, y) for x, row in enumerate(matrix) 
                                        for y, _ in enumerate(row))

Note that this will do a lot of duplicate calculations. Adding memoization is left as an excercise to the reader.

Example:

>>> longest_path(matrix)
(5, [9, 5, 3, 2, 1])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!