前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode329. 矩阵中的最长递增路径

LeetCode329. 矩阵中的最长递增路径

作者头像
mathor
发布2018-07-24 15:28:53
9160
发布2018-07-24 15:28:53
举报
文章被收录于专栏:mathormathor
image
image

 dfs,主函数中枚举起点,然后dfs函数中枚举四个方向进行移动,但是光dfs还不够,因为我们发现存在很多冗余,所以这是一道dfs+dp的问题,resulti表示以i,j为终点的最长递增路径的长度

代码语言:javascript
复制
class Solution {
    public int n,m;
    public int[][] dr = {{-1,0},{1,0},{0,-1},{0,1}};
    public int[][] result = new int[1000][1000];
    public boolean check(int x,int y,int nx,int ny,int[][] matrix) {
        return nx >= 0 && ny >= 0 && nx < n && ny < m && matrix[nx][ny] > matrix[x][y];
    }
    public int dfs(int x,int y,int[][] matrix) {
        int max = 0;
        if(result[x][y] != 1)
            return result[x][y];
        for(int i = 0;i < 4;i++) {
            int nx = x + dr[i][0];
            int ny = y + dr[i][1];
            if(check(x,y,nx,ny,matrix))
                result[x][y] = Math.max(result[x][y],dfs(nx,ny,matrix) + 1);
        }
        return result[x][y];
    }
    public int longestIncreasingPath(int[][] matrix) {
        n = matrix.length;
        if(n == 0)
            return 0;
        m = matrix[0].length;
        int ans = 0;
        for(int i = 0;i < 1000;i++) 
            for(int j = 0;j < 1000;j++) 
                result[i][j] = 1;
        for(int i = 0;i < n;i++) {
            for(int j = 0;j < m;j++) {
                ans = Math.max(ans,dfs(i,j,matrix));
            }
        }
        return ans;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档