码迷,mamicode.com
首页 > 其他好文 > 详细

329. Longest Increasing Path in a Matrix

时间:2016-07-10 06:19:01      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 329. Longest Increasing Path in a Matrix
     * 2016-7-9 by Mingyang
     * 其实这种类型的题目没有想象的那么难,你只需要好好的按照dfs的概念一点一点的走就好了
     * 记住,每个dfs不光是void的,也可以返回一个长度
     */
    public static final int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix.length == 0)
            return 0;
        int m = matrix.length, n = matrix[0].length;
        int[][] cache = new int[m][n];
        int max = 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int len = dfs(matrix, i, j, m, n, cache);
                max = Math.max(max, len);
            }
        }
        return max;
    }
    public int dfs(int[][] matrix, int i, int j, int m, int n, int[][] cache) {
        if (cache[i][j] != 0)
            return cache[i][j];
        int max = 1;
        for (int[] dir : dirs) {
            int x = i + dir[0], y = j + dir[1];
            if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j])
                continue;
      //m,n is the boundry
            int len = 1 + dfs(matrix, x, y, m, n, cache);
            max = Math.max(max, len);
        }
        cache[i][j] = max;
        return max;
    }

 

329. Longest Increasing Path in a Matrix

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5657029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!