48-Longest Increasing Path in a Matrix

题目地址: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).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
//解题思路:遍历图,利用DFS进行每一个节点的前后左右判断是否满足条件,将最大的点赋值全局变量;其中visited数组是起到缓存的作用,以免重复查询,这点借鉴了此答案

class Solution {
    int count=0;
    public int longestIncreasingPath(int[][] matrix) {
         int xLen = matrix.length;
        int yLen = 0;
        if (xLen != 0) {
            yLen = matrix[0].length;
        }
        int[][] visited = new int[xLen][yLen];
        for (int i = 0; i < xLen; i++) {
            for (int k = 0; k < yLen; k++) {
                if (visited[i][k] > 0) {
                    if(visited[i][k] > count){
                        count = visited[i][k];
                    }
                    continue;
                }
                DFS(i, k, matrix, visited, -1);
            }
        }
        return count;
    }
    private  int DFS(int x, int y, int[][] matrix, int[][] visited, int pre) {
       if (x < 0 || y < 0 || y >= matrix[0].length || x >= matrix.length) {
            return 0;
        }
        if (matrix[x][y] <= pre) {
            return 0;
        }
        if (visited[x][y] > 0) {
            return visited[x][y];
        }
        int max1 = Math.max(DFS(x, y + 1, matrix, visited, matrix[x][y]), DFS(x + 1, y, matrix, visited, matrix[x][y]));
        int max2 = Math.max(DFS(x, y - 1, matrix, visited, matrix[x][y]), DFS(x - 1, y, matrix, visited, matrix[x][y]));
        int max = Math.max(max1, max2) + 1;
         count=Math.max(max,count);
        visited[x][y] = max;
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值