Leetcode 329. 矩阵中的最长递增路径
2018-06-25 11:09
387 查看
// 超时的代码 class Solution { public: int n,m; bool check(int x, int y, int x_, int y_, vector<vector<int>>& mat) { // 条件判断 if(x_ < 0 || x_ >= n || y_ < 0 || y_ >= m) { return false; } if(mat[x_][y_] > mat[x][y]) return true; else return false; } // 从起点x,y出发最远可以走多少步 int dfs(int x, int y, vector<vector<int>>& mat) { int m = 0; if(check(x, y, x-1, y, mat)) { m = max(m, dfs(x-1, y, mat) + 1); } if(check(x, y, x+1, y, mat)) { m = max(m, dfs(x+1, y, mat) + 1); } if(check(x, y, x, y-1, mat)) { m = max(m, dfs( x, y-1, mat) + 1); } if(check(x, y, x, y+1, mat)) { m = max(m, dfs(x, y+1, mat) + 1); } return m; } int longestIncreasingPath(vector<vector<int>>& matrix) { n = matrix.size(); if(n==0) return 0; m = matrix[0].size(); if(m==0) return 0; //进行穷举计算 int ans = -1; for(int i=0;i<n;++i) { for(int j=0; j<m; ++j) { ans = max(ans, dfs(i,j,matrix)); } } return ans+1; } };
用深度优先搜索的方式实现代码,结果超时了,有很多冗余的计算在里面,可以使用其他的方法来进行优化。
相关文章推荐
- Leetcode 329. 矩阵中的最长递增路径
- LeetCode 329. Longest Increasing Path in a Matrix(矩阵内的最长递增路径)
- [LeetCode] Longest Increasing Path in a Matrix 矩阵中的最长递增路径
- 动态规划法求解矩阵中最长的递增路径的长度
- leetcode 329. Longest Increasing Path in a Matrix 矩阵中寻找最长递增序列 + 一个典型的深度优先遍历DFS的做法
- leetcode解题之329. Longest Increasing Path in a Matrix Java版 (最长上升路径)
- 51nod 1274 最长递增路径(DP)
- [DP] 51 Nod 1274——最长递增路径
- LeetCode 300. Longest Increasing Subsequence(最长递增子序列)
- 【Codewars-Pyramid Slide Down】(下三角矩阵求最长路径)
- leetcode 300. Longest Increasing Subsequence 最长递增子序列LISS + 十分经典的动态规划DP做法
- [LeetCode] Longest Continuous Increasing Subsequence 最长连续递增序列
- [LeetCode] Longest Line of Consecutive One in Matrix 矩阵中最长的连续1
- 51nod 1274 最长递增路径【dp】
- [51nod1274]最长递增路径
- LeetCode 在矩阵中寻找路径类的动态规划问题
- (LIS)最长递增/递减子序列(带路径)模板 O(NlogN)
- Google算法题:矩阵中的最长上升路径
- [LeetCode] Longest Increasing Subsequence 最长递增子序列的长度
- leetcode 388. Longest Absolute File Path 最长长度文件路径 + 广度优先遍历BFS