leetcode 329. Longest Increasing Path in a Matrix 一个简单的DFS应用

来源:互联网 发布:爱稀奇淘宝网 编辑:程序博客网 时间:2024/06/05 02:44

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.

这道题很简单,直接DFS遍历即可,不过这里使用了一个dp数组来做剪纸处理,属于一个很基本的DFS深度有限遍历的应用。

代码如下:

/* * 没什么就是一个简单的最基本的DFS深度优先遍历的应用 * */class Solution{    public int longestIncreasingPath(int[][] matrix)     {        if(matrix.length<=0 || matrix[0].length <=0)             return 0;        int max=0, n = matrix.length, m = matrix[0].length;        int [][] dp = new int[n][m];        for(int i=0;i<matrix.length;i++)        {            for(int j=0;j<matrix[0].length;j++)            {                max = Math.max(max, maxLen(matrix, Integer.MIN_VALUE, i, j, dp));            }        }        return max;    }    public int maxLen(int[][] matrix, int pre, int i, int j, int[][] dp)    {        if(i<0 || j<0 || i>=matrix.length || j>= matrix[0].length || matrix[i][j] <= pre)             return 0;        else if(dp[i][j] != 0)             return dp[i][j];        else         {            pre = matrix[i][j];            int up = maxLen(matrix, pre, i-1, j, dp) + 1;            int left = maxLen(matrix, pre, i, j-1, dp) + 1;            int right = maxLen(matrix, pre, i, j+1, dp) + 1;            int down = maxLen(matrix, pre, i+1, j, dp) + 1;            dp[i][j] = Math.max(up, Math.max(left, Math.max(right,down)));                 return dp[i][j];        }    }}
阅读全文
0 0
原创粉丝点击