ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 326 矩阵中的最长递增路径

2021-11-15 22:34:18  阅读:151  来源: 互联网

标签:matrix int max 矩阵 dfs vector 326 memory leetcode


深度优先搜索,思路不难,其中重要的是记忆化搜索,就是搜索的时候记录以当前节点为起点的最长路径的长度。贴代码

 1 class Solution {
 2 public:
 3     int res = 0;
 4     int m;
 5     int n;
 6     int longestIncreasingPath(vector<vector<int>>& matrix) 
 7     {
 8         m = matrix.size();
 9         n = matrix[0].size();
10         vector<vector<int>> memory(m,vector<int>(n,1));
11         int res = 1; 
12         for(int i = 0 ; i < m ; i++)
13         {
14             for(int j = 0 ; j < n ; j++)
15             {
16                 if(memory[i][j] == 1)
17                 {
18                     int temp = dfs(matrix,i,j,memory);
19                     if(temp>res)
20                     res = temp;
21                 }
22             }
23         }
24         return res;
25     }
26     int dfs(vector<vector<int>>& matrix,int i,int j,vector<vector<int>>& memory)
27     {
28         if(memory[i][j]!=1)
29         return memory[i][j];
30         int max = 0;
31         int t1 = 0;
32         int t2 = 0;
33         int t3 = 0;
34         int t4 = 0;
35         if(i+1<m && matrix[i+1][j]>matrix[i][j])
36         t1 = dfs(matrix,i+1,j,memory);
37         if(t1>max)
38         max = t1;
39         if(i-1>=0 && matrix[i-1][j]>matrix[i][j])
40         t2 = dfs(matrix,i-1,j,memory);
41         if(t2>max)
42         max = t2;
43         if(j+1<n && matrix[i][j+1]>matrix[i][j])
44         t3 = dfs(matrix,i,j+1,memory);
45         if(t3>max)
46         max = t3;
47         if(j-1>=0 && matrix[i][j-1]>matrix[i][j])
48         t4 = dfs(matrix,i,j-1,memory);
49         if(t4>max)
50         max = t4;
51         memory[i][j] = max+1;
52         return max+1;
53     }
54 };

 

标签:matrix,int,max,矩阵,dfs,vector,326,memory,leetcode
来源: https://www.cnblogs.com/zhaohhhh/p/15558735.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有