leetcode329+二维矩阵上的最长路径,DP加上DFS

https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/

class Solution {
public:
    int dfs(vector>& matrix, vector>& record, int x, int y, int lastVal){
        if(x<0||x>=matrix.size()||y<0||y>=matrix[0].size()) return 0;
        if(matrix[x][y] > lastVal){
            if(record[x][y]!=0) return record[x][y];
            int left = dfs(matrix, record, x, y-1, matrix[x][y])+1;
            int right = dfs(matrix, record, x, y+1, matrix[x][y])+1;
            int top = dfs(matrix, record, x-1, y, matrix[x][y])+1;
            int bottom = dfs(matrix, record, x+1, y, matrix[x][y])+1;
            record[x][y] = max(left, max(right, max(top, bottom)));
            return record[x][y];
        }
        return 0;
    }
    int longestIncreasingPath(vector>& matrix) {
        if(matrix.size()==0) return 0;
        vector temp(matrix[0].size(), 0);
        vector> record(matrix.size(), temp);
        int longest = 0;
        for(int i=0; i

你可能感兴趣的:(Leetcode)