329.Longest Increasing Path in a Matrix.md
Posted antoniosu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了329.Longest Increasing Path in a Matrix.md相关的知识,希望对你有一定的参考价值。
Given an integer matrix, find the length of the longest increasing path.
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的主要内容,如果未能解决你的问题,请参考以下文章
Memoization-329. Longest Increasing Path in a Matrix
329.Longest Increasing Path in a Matrix.md
[leetcode]Memoization-329. Longest Increasing Path in a Matrix
329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径