zoukankan      html  css  js  c++  java
  • 329. Longest Increasing Path in a Matrix(核心在于缓存遍历过程中的中间结果)

    Given an integer matrix, find the length of the longest increasing path.

    From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

    Example 1:

    Input: nums = 
    [
      [9,9,4],
      [6,6,8],
      [2,1,1]
    ] 
    Output: 4 
    Explanation: The longest increasing path is [1, 2, 6, 9].
    

    Example 2:

    Input: nums = 
    [
      [3,4,5],
      [3,2,6],
      [2,2,1]
    ] 
    Output: 4 
    Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

    class Solution {
    public:
        //如果不保存计算过程中的结果,就会超时。利用dp[i][j]来保存矩阵matrix[i][j]这个位置作为起始位置的最长路径的长度。
        bool judgeValid(int x,int y,vector<vector<int>>& matrix){
            return x >= 0 && x <= matrix.size()-1 && y >=0 && y <= matrix[0].size()-1;
        }
        //x,y当前元素坐标。maxLen全局最长路径
        int dfs(vector<vector<int>>& matrix,int x,int y,vector<vector<int>> &dp){
            if(dp[x][y]) return dp[x][y];
            int maxLen = 1;
            vector<vector<int>> dirs = {{1,0},{-1,0},{0,1},{0,-1}};
            for(auto dir:dirs){
                int xx = x+dir[0];
                int yy = y+dir[1];
                if(!judgeValid(xx,yy,matrix) || matrix[xx][yy] <= matrix[x][y]) continue;
                int len = 1+dfs(matrix,xx,yy,dp);
                maxLen = max(len,maxLen);
            }
            dp[x][y] = max(maxLen,dp[x][y]);
            return dp[x][y];
        }
        //要回溯
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            if(matrix.size() == 0) return 0;
            if(matrix[0].size() == 0) return 0;
            int resLen = 1;
            vector<vector<int>> dp(matrix.size(),vector<int>(matrix[0].size(),0));
            for(int i=0;i<matrix.size();i++){
                for(int j=0;j<matrix[0].size();j++){
                    int len = dfs(matrix,i,j,dp);
                    resLen = max(len,resLen);
                }
            }
            return resLen;
        }
    };
  • 相关阅读:
    杨玲 201771010133《面向对象程序设计(java)》第三周学习总结
    杨玲 201771010133《面向对象程序设计(java)》第二周学习总结
    杨玲 201771010133 《面向对象程序设计(java)》第一周学习总结
    bzoj1010 [HNOI2008]玩具装箱toy
    hdu5115 Dire Wolf
    bzoj2880
    bzoj2301 [HAOI2011]Problem b
    bzoj2440 [中山市选2011]完全平方数
    bzoj4448 情报传递
    bzoj4445 小凸想跑步
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/13943889.html
Copyright © 2011-2022 走看看