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
- leetcode 329. Longest Increasing Path in a Matrix 一个简单的DFS应用
- 329.LeetCode Longest Increasing Path in a Matrix(hard)[DFS]
- leetcode 329 : Longest Increasing Path in a Matrix : dfs+dp
- [Leetcode] #329 Longest Increasing Path in a Matrix (DFS)
- 329. Longest Increasing Path in a Matrix DFS解法
- 329. Longest Increasing Path in a Matrix(DFS & DP)
- leetcode Longest Increasing Path in a Matrix
- [LeetCode] Longest Increasing Path in a Matrix
- leetcode: Longest Increasing Path in a Matrix
- Leetcode: Longest Increasing Path in a Matrix
- leetcode:Longest Increasing Path in a Matrix
- [LeetCode]Longest Increasing Path in a Matrix
- [Leetcode]Longest Increasing Path in a Matrix
- Longest Increasing Path in a Matrix | leetcode
- LeetCode Longest Increasing Path in a Matrix
- 【Leetcode】Longest Increasing Path in a Matrix
- LeetCode:Longest Increasing Path in a Matrix
- [leetcode]Longest Increasing Path in a Matrix
- 下面是javascript基础的一些面试题
- html-webpack-plugin
- oracle常用的转换函数
- python多线程之限制同时运行的线程个数
- ArrayList源码解读
- leetcode 329. Longest Increasing Path in a Matrix 一个简单的DFS应用
- 探新Web前端开发(三)
- JQuery中的Ajax语法
- NYOJ 15 括号匹配(二) POJ 2955 Brackets(区间dp)
- lucence基础知识
- 使用gethostnamebyname获取百度官方域名及ip地址
- C#--WinForm基于泛型集合动态填充下拉框
- Linux下Memcache服务器端的安装
- Java生产者与消费者模式的简单写法