leetcode-矩阵中的最长递增路径

class Solution {
    private HashMap<String,Integer> maxmap = new HashMap<>();
    private int[][] matrix;
    private int maxcount = 0;
    private int rowlength;
    private int columnlength;
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix.length==0){
            return 0;
        }
        this.matrix = matrix;
        this.rowlength = this.matrix.length;
        this.columnlength = this.matrix[0].length;
        for(int i=0;i<this.rowlength;i+=1){
            for(int k=0;k<this.columnlength;k+=1){
                this.dfs(i,k,1);
            }
        }
        return this.maxcount;
    }
    public void dfs(int row,int column,int count){
        this.maxcount = Math.max(this.maxcount,count);
        String nowindex = row+" "+column;
        if(this.maxmap.get(nowindex)==null){
            //说明还没有
            this.maxmap.put(nowindex,count);
        }
        else{
            if(this.maxmap.get(nowindex)>=count){
                return;
            }
            else{
             this.maxmap.put(nowindex,count);   
            }
        }
        //然后开始选接下来的路线
        if(row-1>=0 &&  this.matrix[row][column]<this.matrix[row-1][column]){

            this.dfs(row-1,column,count+1);
        }
        if(row+1<this.rowlength &&  this.matrix[row][column]<this.matrix[row+1][column]){

            this.dfs(row+1,column,count+1);
        }
        if(column-1>=0 &&  this.matrix[row][column]<this.matrix[row][column-1]){

            this.dfs(row,column-1,count+1);
        }
        if(column+1<this.columnlength &&  this.matrix[row][column]<this.matrix[row][column+1]){

            this.dfs(row,column+1,count+1);
        }
    }
}

dfs+剪枝

然而速度依然挺慢,400ms....

代码还是很好写,关键的剪枝部分使用hashmap去缓存当前位置最大的长度,因为如果之后有节点到了某位置但该节点目前的最大长度还没有hashmap已有的大,那么就不需要再递归下去了。

另外其他很快的答案里面有人缓存的方法是对某位置的最大长度(不是当前,直接是最大)进行缓存,这样速度更快,算出一个可以很快算出另一个。他的dfs写法和我平时写的不太一样,他的dfs是要返回值的,返回某位置的最大长度。

发布了48 篇原创文章 · 获赞 0 · 访问量 4329

猜你喜欢

转载自blog.csdn.net/weixin_41327340/article/details/103788026