LeetCode 329.矩阵中的最长递增路径

给定一个 m x n 整数矩阵 matrix ,找出其中 最长递增路径 的长度。

对于每个单元格,你可以往上,下,左,右四个方向移动。 你 不能 在 对角线 方向上移动或移动到 边界外(即不允许环绕)。

动态规划-记忆化搜索
对每个点周围四个点中比它小的点进行搜索 其中最长路径+1为当前点最长路径
对搜索过的点用二维数组记录

class Solution {
    int[][] dp;
    int[][] flag;
    public int longestIncreasingPath(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        if(matrix == null || m == 0 || n == 0)
            return 0;
        dp = new int[m][n];
        flag = new int[m][n];
        int ans = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                dp[i][j] = search(matrix, i, j);
                ans = Math.max(ans, dp[i][j]);
            }
        }
        return ans;


    }
    int[] cx = {0, 1, 0, -1};
    int[] cy = {1, 0, -1, 0};
    private int search(int[][] matrix, int x, int y){
        if(flag[x][y] == 1){
            return dp[x][y];
        }
        int ans = 1;
        for(int i = 0; i < 4; i++){
            int newx = x + cx[i];
            int newy = y + cy[i];
            if(!isValid(matrix, newx, newy))
                continue;
            if(matrix[newx][newy] < matrix[x][y])
                ans = Math.max(ans, search(matrix, newx, newy) + 1);
        }
        flag[x][y] = 1;
        dp[x][y] = ans;
        return ans;
    }
    private boolean isValid(int[][] matrix, int x, int y){
        int m = matrix.length;
        int n = matrix[0].length;
        if(x < 0 || y < 0 || x >= m || y >= n)
            return false;
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值