zoukankan      html  css  js  c++  java
  • LeetCode-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).

    题目大意

    在一个整数矩阵中,寻找一条最长的递增路径的长度。

    (路径的方向只能为上、下、左、右四个方向)

    示例

    E1

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

    E2

    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.

    解题思路

    基于DFS的思想,为了能够减少重复计算某个位置的最长路径的次数,可以利用一个cache数组来存储已经计算的结果,可以有效减少时间复杂度。

    复杂度分析

    时间复杂度:O(N2)

    空间复杂度:O(N2)

    代码

    class Solution {
    public:
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            if(matrix.size() == 0 || matrix[0].size() == 0)
                return 0;
            // 保存该位置已经计算过的最长递增路径结果
            vector<vector<int> > cache(matrix.size(), vector<int>(matrix[0].size(), 0));
            int res = 1;
            // 依次访问矩阵的所有位置,分别进行DFS遍历
            for(int i = 0; i < matrix.size(); ++i) {
                for(int j = 0; j < matrix[0].size(); ++j) {
                    res = max(res, dfs(matrix, cache, i, j));
                }
            }
            
            return res;
        }
        
        int dfs(vector<vector<int> >& m, vector<vector<int> >& cache, int i, int j) {
            // 如果当前位置之前已经计算过,则直接返回结果
            if(cache[i][j] != 0)
                return cache[i][j];
            
            int len = 1;
            // 依次判断四个方向是否符合条件,若符合条件则递归进行DFS
            for(int k = 0; k < 4; ++k) {
                int x = i + dir[k][0], y = j + dir[k][1];
                if(x >= 0 && x < m.size() && y >= 0 && y < m[0].size() && m[x][y] > m[i][j]) {
                    len = max(len, dfs(m, cache, x, y) + 1);
                }
            }
            // 记录该位置的最长递增路径的长度
            cache[i][j] = len;
            return len;
        }
        
    private:
        vector<vector<int> > dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    };
  • 相关阅读:
    Nginx之HTTP过滤模块
    Nginx之编写HTTP模块
    Nginx之最简单的反向代理机制分析
    Nginx之搭建反向代理实现tomcat分布式集群
    Nginx之configure选项
    Nginx-HTTP之ngx_http_top_body_filter
    Nginx-HTTP之ngx_http_top_header_filter
    Nginx-HTTP之静态网页访问流程分析二
    error: ‘Poco::UInt16’ has not been declared
    字符数组中查找字符串或字符数组
  • 原文地址:https://www.cnblogs.com/heyn1/p/11195228.html
Copyright © 2011-2022 走看看