zoukankan      html  css  js  c++  java
  • leetcode 329. Longest Increasing Path in a Matrix

    329. Longest Increasing Path in a Matrix

    https://www.cnblogs.com/grandyang/p/5148030.html

    这个题是在二维数组中找递增序列的最长长度。

    因为使用dfs都是从当前位置进行搜索,所以每次dp计算的值是以当前为起点的最长长度。

    这里使用了一个二维数组记录每个位置最长长度,在dfs递归的时候,同时也起到了之前visited数组的作用,只要这个位置的dp值不为0,就表示已经访问过了,可以直接返回数值。

    还有这里的越界处理,即

    if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[i][j] >= matrix[x][y])
    continue;

    不是像number of islands那样直接进入递归就判断,而是先变化坐标生成新的坐标判断新的坐标是否符合。number of islands两种方法都可以,但这个题只能使用这种方式,因为只有这种方式才能得到前后两个位置之间的数值关系,才能确保是递增的。

    class Solution {
    public:
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            int m = matrix.size();
            if(m <= 0)
                return 0;
            int n = matrix[0].size();
            if(n <= 0)
                return 0;
            vector<vector<int>> dp(m,vector<int>(n,0));
            int res = 1;
            for(int i = 0;i < m;i++){
                for(int j = 0;j < n;j++){
                    res = max(res,dfs(matrix,dp,i,j));
                }
            }
            return res;
        }
        int dfs(vector<vector<int>>& matrix,vector<vector<int>>& dp,int i,int j){
            if(dp[i][j])
                return dp[i][j];
            dp[i][j] = 1;
            int max_num = 1;
            for(auto dir : dirs){
                int x = i + dir[0];
                int y = j + dir[1];
                if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[i][j] >= matrix[x][y])
                    continue;
                int length = 1 + dfs(matrix,dp,x,y);
                max_num = max(max_num,length);
            }
            dp[i][j] = max_num;
            return max_num;
        }
    private:
        vector<vector<int>> dirs{{-1,0},{1,0},{0,-1},{0,1}};
    };
  • 相关阅读:
    线程池ThreadPoolExecutor
    常用引擎+存储过程
    在浏览器中输入www.baidu.com后执行的全过程
    win端git连接私服仓库+上传本地项目+从服务器下载文件到win
    TCP的三次握手和四次挥手+TCP和UDP的区别
    2017网易---计算糖果
    ubuntu下wireshark+scapy+tcpreply
    网易2017---数列还原
    2017网易---藏宝图
    2017网易---不要二
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10942316.html
Copyright © 2011-2022 走看看