您的位置:首页 > 其它

leetcode329——Longest Increasing Path in a Matrix

2018-03-21 15:16 375 查看
题目大意:给出一个矩阵,在这个矩阵中找出最长的一条路径,路径中的数字按从小到大升序。
分析:拓扑排序或者dfs+dp。
          拓扑排序的思路:将矩阵中每个数字表上序号,从每个结点出发向它上下左右比它大的结点画线,建好图后拓扑排序找顺序即可。
          dfs思路:dfs搜索四个方向,dp记忆化提高效率,就是说已经记录过步长的位置就没必要再次搜索了。
代码:dfs转载自https://www.cnblogs.com/luntai/p/6936588.html
class Solution {
public:
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, n, m;
int dfs(int x, int y, vector<vector<int>>& matrix, vector<vector<int>>&steps){
if(steps[x][y]) return steps[x][y];
int maxSteps = 0; // record the longest path steps from (x, y)
for(int i = 0; i < 4; i ++){
int nx = dir[i][0] + x, ny = dir[i][1] + y, tmp = 0;
if(nx >= 0 && ny >= 0 && nx < n && ny < m && matrix[nx][ny] > matrix[x][y]){
maxSteps = max(maxSteps, dfs(nx, ny, matrix, steps));
}
}
steps[x][y] = maxSteps + 1; // + 1 for cur(x, y)
return steps[x][y];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.size() == 0) return 0;
n = matrix.size(), m = matrix[0].size();
int ans = 0;
vector<vector<int>>steps(n, vector<int>(m, 0));
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
ans = max(ans, dfs(i, j, matrix, steps));
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: