【python-leetcode329-深度優先搜索】矩陣中的最長遞增路徑


給定一個整數矩陣,找出最長遞增路徑的長度。

對於每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。

示例 1:

輸入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
輸出: 4
解釋: 最長遞增路徑為 [1, 2, 6, 9]。
示例 2:

輸入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
輸出: 4
解釋: 最長遞增路徑是 [3, 4, 5, 6]。注意不允許在對角線方向上移動。

class Solution:
    def longestIncreasingPath(self, matrix):
        if not matrix:
            return 0
        row_n = len(matrix)
        col_n = len(matrix[0])
        res = 1
        resut_save = [[0 for _ in range(col_n)] for _ in range(row_n)]
        for i in range(row_n):
            for j in range(col_n):
                res = max(res, self.dfs(matrix, i, j, resut_save))
        return res
    def dfs(self,matrix, i, j, resut_save):
        if resut_save[i][j] != 0:
            return  resut_save[i][j]
        dirctions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        res = 1
        for dx, dy in dirctions:
            x = i + dx
            y = j + dy
            if 0<= x < len(matrix) and 0<= y < len(matrix[0]) and matrix[x][y] > matrix[i][j]:
                res = max(res, self.dfs(matrix, x, y, resut_save) + 1)
        resut_save[i][j] = res
        return res

s=Solution()
res=s.longestIncreasingPath([[9,9,4],[6,6,8],[2,1,1]])
print(res)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM