leetcode 329. Longest Increasing Path in a Matrix

leetcode 329. Longest Increasing Path in a Matrix


下面这个解法的错误之处在于,最长路径不会遵循左上 或 右上 这样的法则,可以同时包含两种模式。

class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        int m = matrix.length;
        if(m==0) return 0;
        int n = matrix[0].length;
        int[][] res = new int[m][n];
        for(int i=0;i=0&&matrix[i][j]>matrix[i-1][j])  res[i][j] = res[i-1][j] + 1;
                if(j-1>=0&&matrix[i][j]>matrix[i][j-1]&&res[i][j-1]+1>res[i][j])  res[i][j] = res[i][j-1]+1;
            }
        }
        int r = 0;
        for(int i=m-1;i>=0;i--){
            for(int j=n-1;j>=0;j--){
                if(i+1matrix[i+1][j]&&res[i+1][j]+1>res[i][j])  res[i][j] = res[i+1][j]+1;
                if(j+1matrix[i][j+1]&&res[i][j+1]+1>res[i][j])  res[i][j] = res[i][j+1]+1;
                if(res[i][j]>r) r=res[i][j];
            }
         }
        return r;
    }
}



正确解法:  dfs + dp


class Solution {
    private int m,n;
    private int[][] cached;
    private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix==null) return 0;
        if(matrix.length==0) return 0;
        m = matrix.length;
        n = matrix[0].length;
        cached = new int[m][n];
        int ans = 0;
        for(int i=0;i=0&&n_j>=0&&n_imatrix[i][j]){
                cached[i][j] = Math.max(cached[i][j], dfs(matrix, n_i, n_j));
            }
        }
        return  ++cached[i][j];
    }
    
}





你可能感兴趣的:(算法)