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.

    难度系数

    Hard

    解法:dfs,保存每次的求解结果,否则会TLE

    class Solution {
        vector<int> si={0,0,-1,1};
        vector<int> sj={-1,1,0,0};
        
        int search(vector<vector<int>> & lp, vector<vector<int>>& matrix, int i, int j, int m, int n){
            if(lp[i][j] != -1) return lp[i][j];
            
            lp[i][j] = 1;
            for(int k=0; k<si.size(); k++){
                int di = i+si[k], dj = j+sj[k];
                if(di<0 || di>=m || dj<0 || dj>=n) continue;
                if(matrix[i][j]>matrix[di][dj]){
                    lp[i][j] = max(lp[i][j], 1+search(lp, matrix, di, dj, m, n));
                }
            }
            return lp[i][j];
        }
        
        
    public:
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            if(matrix.size()==0 || matrix[0].size()==0) return 0;
            int m=matrix.size(), n=matrix[0].size();
            //lp是记录以某个节点开始的最长路径
            vector<vector<int>> lp(m, vector<int>(n, -1));
            int ret = 0;
            for(int i=0; i<m; i++)
                for(int j=0; j<n; j++)
                    ret = max(ret, search(lp, matrix, i, j, m, n));
     
            return ret;
        }
    };
  • 相关阅读:
    FFT学习笔记
    FWT(Fast Walsh Transformation)快速沃尔什变换学习笔记
    GMS2游戏开发学习历程
    [BZOJ3238][AHOI2013]差异 [后缀数组+单调栈]
    Trie树简单讲解
    自己的题
    小技巧
    编程注意事项
    构造方法
    递归
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12729325.html
Copyright © 2011-2022 走看看