码迷,mamicode.com
首页 > 其他好文 > 详细

329.Longest Increasing Path in a Matrix.md

时间:2020-04-19 01:25:14      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:color   incr   you   for   lan   ade   pat   col   最长路径   

题目描述

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;
    }
};

 

329.Longest Increasing Path in a Matrix.md

标签:color   incr   you   for   lan   ade   pat   col   最长路径   

原文地址:https://www.cnblogs.com/AntonioSu/p/12729325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!