Leetcode 329. Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

思路:

  1. 对数组中每个元素A,都尝试寻找以A为起点的最长路径。
  2. 用一个最大值路径变量记录当前寻找到的最长路径。
  3. 由于尝试遍历每个元素,数组中某些位置会被重复查找,此时可以通过哈希表来记录以当前位置为起点的最长路径,如果已经查找过,则直接返回值。如果没有被查找过,在算出最大路径值以后存放到哈希表中,下次就不用再计算了。
public class LIPInMatrix329 {

    private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private int m, n;

    public int longestIncreasingPath(int[][] matrix) {
        if (matrix.length == 0) {
            return 0;
        }
        m = matrix.length; n = matrix[0].length;
        int[][] cache = new int[m][n];
        int ans = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                ans = Math.max(ans, dfs(matrix, i, j, cache));
            }
        }
            
        return ans;
    }

    private int dfs(int[][] matrix, int x, int y, int[][] cache) {
        if (cache[x][y] != 0) {
            return cache[x][y];
        }
        
        cache[x][y] = 1;
        for (int[] d : dirs) {
            int tx = x + d[0], ty = y + d[1];
            if (0 <= tx && tx < m && 0 <= ty && ty < n && matrix[tx][ty] > matrix[x][y]) {
                cache[x][y] = Math.max(cache[x][y], 1 + dfs(matrix, tx, ty, cache));
            }
        }
        return cache[x][y];
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,162评论 0 10
  • 今晚由一饭局匆匆而归,按耐不住心中的念头,借助这手机屏幕小小的空间,写下些许感受吧 今晚请客的是一位母亲,刚刚送孩...
    dmg09825阅读 2,744评论 0 0
  • 日本留学生江歌被杀害,刘鑫的所做所为让我看到人性可怕的一面,原来这个世界上不是所有人都可以被称作人,不是所有人都能...
    鸠崎阅读 5,135评论 0 0
  • "妈妈,我告诉你我想了一首诗……" "是吗?那你写下来吧!" "你怎么会想起柳树了呢?" "昨天看风景时看见了。"...
    小小丫头yjy阅读 2,880评论 0 1
  • 这样的景,陪我度过多少年。 有眼才能看得透。 有笔才能写得动人。 怀着爱惜在这忙碌的生活之中浮到心头又复随即消失的...
    青衫湿旧阅读 1,072评论 7 12