329. Longest Increasing Path in a Matrix
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了329. 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.
public class Solution { public int longestIncreasingPath(int[][] matrix) { if(matrix==null||matrix.length==0) return 0; int row=matrix.length,col=matrix[0].length; int result[][]=new int[row][col]; //store the longest path at every node int max=1; for(int[]arr:result){ Arrays.fill(arr,-1); } for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ findPath(matrix,result,i,j); max=Math.max(result[i][j],max); } } return max; } private void findPath(int[][]matrix,int result[][],int i,int j){ int row=matrix.length,col=matrix[0].length; int xPos[]={0,0,1,-1}; int yPos[]={1,-1,0,0}; int max=1; for(int k=0;k<4;k++){ //at four direction int nX=xPos[k]+i; int nY=yPos[k]+j; if(nX>=row||nX<0||nY>=col||nY<0){ //skip when out of boundary continue; } if(matrix[nX][nY]>matrix[i][j]){ if(result[nX][nY]<0){ //haven‘t visited [nX,nY] findPath(matrix,result,nX,nY); } max=Math.max( 1+result[nX][nY],max); } } result[i][j]=max; } }
答案一:用数组表示当前元素拥有的最大增长path,上下左右四个方向用0,±1表示,很巧妙,然后是dfs
class Solution { public int longestIncreasingPath(int[][] matrix) { int max = 0; if(matrix.length == 0) return 0; int[][] holder = new int[matrix.length][matrix[0].length]; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ int _max = pathFinder(matrix, holder, Integer.MIN_VALUE, i, j); max = _max > max ? _max : max; } } return max; } private int pathFinder(int[][] matrix, int[][] dp, int last, int v, int w){ if(v < 0 || w < 0 || v == matrix.length || w == matrix[0].length || matrix[v][w] <= last) return 0; if(dp[v][w] > 0){ return dp[v][w]; } int val = pathFinder(matrix, dp, matrix[v][w], v-1, w); val = Math.max(pathFinder(matrix, dp, matrix[v][w], v+1, w), val); val = Math.max(pathFinder(matrix, dp, matrix[v][w], v, w-1), val); val = Math.max(pathFinder(matrix, dp, matrix[v][w], v, w+1), val); dp[v][w] = ++val; return val; } }
答案2更厉害了,但是本质和1一样
以上是关于329. Longest Increasing Path in a Matrix的主要内容,如果未能解决你的问题,请参考以下文章
Memoization-329. Longest Increasing Path in a Matrix
329.Longest Increasing Path in a Matrix.md
[leetcode]Memoization-329. Longest Increasing Path in a Matrix
329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径
Leetcode之深度优先搜索(DFS)专题-DFS+记忆化 329. 矩阵中的最长递增路径(Longest Increasing Path in a Matrix)