Leetcode: Longest Increasing Path in a Matrix
2016-01-25 10:42
393 查看
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:
use a two dimensional matrix dp[i][j] to store the length of the longest increasing path starting at matrix[i][j]
transferring function is: dp[i][j] = max(dp[i][j], dp[x][y] + 1), where dp[x][y] is its neighbor with matrix[x][y] > matrix[i][j]
public class Solution { int[][] dp; int[][] directions = new int[][]{{-1,0},{1,0},{0,-1},{0,1}}; int m; int n; int[][] mx; public int longestIncreasingPath(int[][] matrix) { if (matrix==null || matrix.length==0 || matrix[0].length==0) return 0; m = matrix.length; n = matrix[0].length; dp = new int[m] ; mx = matrix; int result = 0; for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { dp[i][j] = Integer.MIN_VALUE; } } for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { result = Math.max(result, DFS(i,j)); } } return result; } public int DFS(int i, int j) { if (dp[i][j] != Integer.MIN_VALUE) return dp[i][j]; dp[i][j] = 1; for (int[] dir : directions) { int x = i + dir[0]; int y = j + dir[1]; if (x<0 || y<0 || x>=m || y>=n || mx[x][y]<=mx[i][j]) continue; dp[i][j] = Math.max(dp[i][j], DFS(x,y)+1); } return dp[i][j]; } }
相关文章推荐
- 安装或者更换cocoapods版本出现的问题
- 关于python-NameError: global name 'platform' is not defined
- Linux Source命令及脚本的执行方式解析
- PDF文件中的数字签名之(在一个PDF文件的签名代表)
- mysql 1449 : The user specified as a definer ('root'@'%') does not exist 解决方法
- Lua学习笔记-table中的混合风格&多项式求和
- Virtual Initialization - 虚初始化
- Android开发之获取状态栏高度、屏幕的宽和高
- Spark MLlib实现的广告点击预测–Gradient-Boosted Trees
- 【MVC框架】路由机制
- 商业英语句型13
- CRLF injection 简单总结
- jQuery validate
- Selenium webdriver处理alert、confirm弹出框
- BZOJ 4000: [TJOI2015]棋盘( 状压dp + 矩阵快速幂 )
- org.jdom 解析xml
- css怪异模式总结
- [leetcode] 34. Search for a Range
- 很多时候我都很庆幸自己能够成为一个程序员,为什么呢?
- 客制化物料搬运单流程