329. Longest Increasing Path in a Matrix
2017-12-27 17:20
274 查看
1、题目描述
输入一个2维矩阵,返回矩阵中最长的上升路径长度。
2、思路
DFS+Memoization
用一个同样大小的2维矩阵,记录从每个位置出发的最长上升路径是多少,初始化为1。
对于每个位置,开始dfs,找出四个方向上,比当前位置的数字大,且最长上升路径最长的值,这个值+1是从当前位置出发的值。
找出最大值。
3、代码
输入一个2维矩阵,返回矩阵中最长的上升路径长度。
2、思路
DFS+Memoization
用一个同样大小的2维矩阵,记录从每个位置出发的最长上升路径是多少,初始化为1。
对于每个位置,开始dfs,找出四个方向上,比当前位置的数字大,且最长上升路径最长的值,这个值+1是从当前位置出发的值。
找出最大值。
3、代码
int longestIncreasingPath(vector<vector<int>>& matrix) { int n = matrix.size(); if(n==0) return 0; int m = matrix[0].size(); vector<vector<int>> cache(n,vector<int>(m,1)); int ans = 1; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int ans1 = dfs(matrix,n,m,i,j,cache); ans=max(ans1,ans); } } return ans; } int xx[4]={0,0,1,-1}; int yy[4]={1,-1,0,0}; int dfs(vector<vector<int>>& matrix,int n,int m,int x,int y,vector<vector<int>>& cache){ if(cache[x][y]>1) return cache[x][y]; for(int i=0;i<4;i++){ int nx = x+xx[i]; int ny = y+yy[i]; if(nx>=0&&nx<n&&ny>=0&&ny<m&&matrix[nx][ny]>matrix[x][y]){ if(cache[nx][ny]>1) cache[x][y]=max(cache[x][y],1+cache[nx][ny]); else{ int t = 1+dfs(matrix,n,m,nx,ny,cache); cache[x][y]=max(cache[x][y],t); } } } return cache[x][y]; }
相关文章推荐
- LeetCode--329. Longest Increasing Path in a Matrix
- leetcode-329. Longest Increasing Path in a Matrix
- [leetcode-329]Longest Increasing Path in a Matrix(java)
- [Leetcode] #329 Longest Increasing Path in a Matrix (DFS)
- leetcode 329 : Longest Increasing Path in a Matrix : dfs+dp
- Leetcode 329, Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- [leetcode] 329. Longest Increasing Path in a Matrix
- [LeetCode 329] Longest Increasing Path in a Matrix
- leetcode329——Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- LeetCode-329.Longest Increasing Path in a Matrix
- leetcode 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- leecode 解题总结:329. Longest Increasing Path in a Matrix
- LeetCode—329. Longest Increasing Path in a Matrix