Leetcode 329. Longest Increasing Path in a Matrix (python+cpp)

努利!奮鬥!發表於2020-12-18

題目

在這裡插入圖片描述

解法1:dfs暴力

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        def dfs(i,j,prev):
            if i<0 or i>=m or j<0 or j>=n or matrix[i][j]<=prev:
                return 0
            #print(i,j)
            tmp = 0
            tmp = max(dfs(i+1,j,matrix[i][j]),dfs(i,j+1,matrix[i][j]),dfs(i-1,j,matrix[i][j]),dfs(i,j-1,matrix[i][j])) + 1
            return tmp
        
        if not matrix or not matrix[0]:
            return 0
        
        m,n = len(matrix),len(matrix[0])
        #dfs(0,1,float('-inf'))
        ans = 0
        for i in range(m):
            for j in range(n):
                print((i,j),dfs(i,j,float('-inf')))
                ans = max(dfs(i,j,float('-inf')),ans)
        
        return ans

解法2:dfs+memorization

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        def dfs(i,j,prev):
            if i<0 or i>=m or j<0 or j>=n or matrix[i][j]<=prev:
                return 0
            if memo[i][j] != float('-inf'):
                return memo[i][j]
            memo[i][j] = max(dfs(i+1,j,matrix[i][j]),dfs(i,j+1,matrix[i][j]),dfs(i-1,j,matrix[i][j]),dfs(i,j-1,matrix[i][j])) + 1
            return memo[i][j]
        
        if not matrix or not matrix[0]:
            return 0
        
        m,n = len(matrix),len(matrix[0])
        ans = 0
        memo = [[float('-inf')]*n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                ans = max(dfs(i,j,float('-inf')),ans)
        
        return ans

C++版本:

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int ans = 0;
        int m = matrix.size(), n = matrix[0].size();
        vector<vector<int>> memo(m,vector<int>(n,-INT_MAX));
        for (int i=0;i<matrix.size();i++){
            for (int j=0;j<matrix[0].size();j++){
                ans = max(ans,dfs(i,j,-INT_MAX,memo,matrix));
            }
        }
        return ans;
    }
    int dfs(int i, int j, int prev, vector<vector<int>>& memo, vector<vector<int>>& matrix){
        if (i<0 || i>=matrix.size() || j<0 || j>=matrix[0].size() || matrix[i][j]<=prev) {
            return 0;
        }
        if (memo[i][j] != -INT_MAX) return memo[i][j];
        memo[i][j] = max(dfs(i+1,j,matrix[i][j],memo,matrix)+1,memo[i][j]);
        memo[i][j] = max(dfs(i,j+1,matrix[i][j],memo,matrix)+1,memo[i][j]);
        memo[i][j] = max(dfs(i-1,j,matrix[i][j],memo,matrix)+1,memo[i][j]);
        memo[i][j] = max(dfs(i,j-1,matrix[i][j],memo,matrix)+1,memo[i][j]);
        return memo[i][j];
        
    }
};

相關文章