leetcode(329)矩阵中的最大递增路径

矩阵中的最大递增路径

解题思路:动态规划

class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix.length==0||matrix[0].length==0){
            return 0;
        }
        int xlen = matrix.length;
        int ylen = matrix[0].length;
        int[][][] flags = new int[xlen][ylen][2];
        for(int i=0;i<xlen;i++){
            for(int j=0;j<ylen;j++){
                for(int k=0;k<2;k++){
                    flags[i][j][k]=1;
                }
            }
        }
        int cur = 0;
        boolean ischange = false;
        int ans =1;
        while(true){
            ischange = false;
            for(int i=0;i<xlen;i++){
                for(int j=0;j<ylen;j++){
                    if(i-1>=0&&matrix[i][j]>matrix[i-1][j]&&flags[i][j][1-cur]<flags[i-1][j][cur]+1){
                        flags[i][j][1-cur] = flags[i-1][j][cur]+1;
                    }
                    if(j-1>=0&&matrix[i][j]>matrix[i][j-1]&&flags[i][j][1-cur]<flags[i][j-1][cur]+1) {
                        flags[i][j][1-cur] = flags[i][j-1][cur]+1;
                    }
                    if(i+1<xlen&&matrix[i][j]>matrix[i+1][j]&&flags[i][j][1-cur]<flags[i+1][j][cur]+1) {
                        flags[i][j][1-cur] = flags[i+1][j][cur]+1;
                    }
                    if(j+1<ylen&&matrix[i][j]>matrix[i][j+1]&&flags[i][j][1-cur]<flags[i][j+1][cur]+1) {
                        flags[i][j][1-cur] = flags[i][j+1][cur]+1;
                    }
                    if(flags[i][j][1-cur]!=flags[i][j][cur]) {
                        ischange = true;
                    }
                }
            }
            if(ischange) {
                cur = 1-cur;
                ans++;
            }else {
                return ans;
            }
        }
    }
}

 另一种方法:

解题思路:dfs+记忆矩阵

posted @ 2019-07-08 20:49  海平面下的我们  阅读(373)  评论(0编辑  收藏  举报