美文网首页动态规划
329. Longest Increasing Path in

329. Longest Increasing Path in

作者: FlynnLWang | 来源:发表于2016-12-31 22:13 被阅读0次

    Question

    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).
    Example 1:

    nums = [
    [9,9,4],
    [6,6,8],
    [2,1,1]
    ]

    Return 4
    The longest increasing path is [1, 2, 6, 9].

    Example 2:

    nums = [
    [3,4,5],
    [3,2,6],
    [2,2,1]
    ]

    Return 4
    The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.


    Code

    public class Solution {
        private int[] di = {1, 0, -1, 0};
        private int[] dj = {0, 1, 0, -1};
        private int max = 1;
        
        public int longestIncreasingPath(int[][] matrix) {
            if (matrix == null || matrix.length == 0) return 0;
            int m = matrix.length, n = matrix[0].length;
            int[][] dp = new int[m][n];
            
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    helper(dp, matrix, i, j);
                }
            }
            
            return max;
        }
        
        public int helper(int[][] dp, int[][] matrix, int i, int j) {
            if (dp[i][j] != 0) return dp[i][j];
            
            int m = matrix.length, n = matrix[0].length;
            
            dp[i][j] = 1;
            for (int k = 0; k < 4; k++) {
                int ni = i + di[k];
                int nj = j + dj[k];
                if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                    if (matrix[i][j] > matrix[ni][nj]) {
                        dp[i][j] = Math.max(dp[i][j], helper(dp, matrix, ni, nj) + 1);
                    }
                }
            }
            max = Math.max(max, dp[i][j]);
            
            return dp[i][j];
        }
    }
    

    Solution

    DFS + 动态规划 + 记忆化搜索。

    由于动态规划的初始起点不好确定,因此使用动态规划 + 记忆化搜索的方法完成。

    dp[i][j]表示以matrix[i][j]为终点的最长递增路径的长度。通过DFS向四周搜索,如果matrix[四周i][四周j]小于matrix[i][j],使用状态转移函数dp[i][j] = Math.max(dp[i][j], helper(dp, matrix, ni, nj) + 1); 最后返回dp中的最大值即可。

    相关文章

      网友评论

        本文标题:329. Longest Increasing Path in

        本文链接:https://www.haomeiwen.com/subject/efsbvttx.html